0

我有这堂课:

public class MyClass {
     public string GetText() {
         return "text";
     }
}

我想要的是有一个通用的缓存方法。如果调用 GetText,我想拦截这个调用,比如;

public T MethodWasCalled<T>(MethodInfo method) {
    if(Cache.Contains(method.Name)) {
        return Cache[method.Name] as T;
    }
    else {
        T result = method.Invoke();
        Cache.Add(method.Name, result);
        return result;
    }
}

我希望上面解释了我想要完成的事情。对此有什么好的策略?

4

2 回答 2

2

If you're using .NET 4, take a look at Lazy<T>.

public class MyClass {
    private Lazy<string> _text = new Lazy<string>(
        () => {
            return "text"; // expensive calculation goes here
        });

    public string GetText() {
        return _text.Value;
    }
}

The code inside the lambda will only be executed once. It's even threadsafe by default.

于 2010-08-24T14:44:17.507 回答
2

PostSharp的边界方面可能是您所需要的。

一些阐述:

PostSharp是一个构建过程库,它在编译时将 IL 注入二进制文件,以公开常规 .NET 范围内不可用的功能。

边界方面允许您在成员访问之前和之后执行代码。实际上“包装”了调用,让你做一些奇特的逻辑。

于 2010-08-23T22:37:51.853 回答