C#4 Intercept method call
I have this class:
public class MyClass {
public string GetText() {
return "text";
}
}
What I want is to have a generic caching method. If GetText is called, I want to intercept this call, something like;
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;
}
}
I hope the ab开发者_运维技巧ove explains what I want to accomplish. What would be a good strategy for this?
PostSharp's Boundry Aspect may be what you need.
Some Elaboration:
PostSharp is a build-process library that injects IL into your binary at compile time to expose functionality not availiable within the bounds of regular .NET.
The Boundry Aspect allows you to execute code before and after a member-access. In-effect "wrapping" the call, letting you do fancy logic.
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.
精彩评论