C#:如何在调用事件的方法上创建属性? [英] C#: How to create an attribute on a method triggering an event when it is invoked?
问题描述
在C#或.NET中,通常是否可以在方法上创建一个属性,该方法在调用该方法时会触发事件?理想情况下,我将能够在调用该方法之前和之后运行自定义操作.
Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.
我的意思是这样的:
[TriggersMyCustomAction()]
public void DoSomeStuff()
{
}
I am totally clueless how to do it or if it possible at all, but System.Diagnostic.ConditionalAttribute might do a similar thing in the background. I am not sure though.
编辑:由于我的具体情况,我忘记提及了,性能并不是真正的问题.
EDIT: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.
推荐答案
我知道如何做到这一点的唯一方法是使用 PostSharp .它可以对您的IL进行后处理,并可以执行您要求的操作.
The only way I know how to do this is with PostSharp. It post-processes your IL and can do things like what you asked for.
这篇关于C#:如何在调用事件的方法上创建属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!