How to wrap a method via attributes?

2019-01-12 02:54发布

问题:

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).

回答1:

AOP is possible in .NET. Here's an article about it. And here's a list of AOP frameworks for .NET.



回答2:

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...



回答3:

You can do this without having to use a different compiler if you use PostSharp.



回答4:

I wrote some stuff about AOP on .Net here: Help and Information about Aspect Oriented Programming



回答5:

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.



标签: c# attributes