How to wrap a method via attributes?
I'm wondering if it's possible to wrap a method only by adding an attribute.
Example: I want to log the execution time a method takes.
[LogTimings]
public void work()
{
..
}
开发者_如何学编程
This is kind of wrapping a method into another one (see this python implementation).
AOP is possible in .NET. Here's an article about it. And here's a list of AOP frameworks for .NET.
Have a look at PostSharp, an AOP framework for .NET.
In terms of logging and timing, there's also a framework called Gibraltar which integrates with PostSharp and which should make it easier to collect and use the results. I keep meaning to get round to trying it...
Using only the standard .NET framework library, you would have to create the wrap functionality by deriving from System.Runtime.Remoting.Proxies.RealProxy
.
This functionality you then can apply to your class, but this class has to derive from System.MarshalByRefObject
.
This is quite some restriction, that's why you might want to look at 3rd party components like PostSharp.
You can do this without having to use a different compiler if you use PostSharp.
I wrote some stuff about AOP on .Net here: Help and Information about Aspect Oriented Programming
精彩评论