How to wrap a method via attributes?

2019-01-12 03:14发布

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

标签: c# attributes
5条回答
贼婆χ
2楼-- · 2019-01-12 03:39

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

查看更多
The star\"
3楼-- · 2019-01-12 03:40

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.

查看更多
你好瞎i
4楼-- · 2019-01-12 03:48

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

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-12 03:53

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

查看更多
劳资没心,怎么记你
6楼-- · 2019-01-12 03:56

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

查看更多
登录 后发表回答