C# 属性修改方法
全部。也许我没有足够的谷歌搜索,但我找不到关于这个问题的任何例子。
在 C# 中是否可以创建一个自定义属性,该属性应用于类并修改其所有方法?例如,添加 Console.WriteLine("Hello, i'm modded method");
作为第一行(或者如果在运行时完成,则它是 IL 等效项)?
all. Maybe i've not googled enough, but i can't find any example on this question.
It is possible in C# to create an custom attribute which, applied to a class, modifies all of its methods? For example, adds Console.WriteLine("Hello, i'm modified method");
as a first line (or it's IL equivalent if it's done at runtime)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以执行此操作,但不行,它不是内置于 C# 中的。正如 Eric 所说,这种技术被称为面向方面编程。
我在工作中使用过PostSharp,它非常有效。它在编译时工作,并使用 IL 编织,而不是其他 AOP 技术。
例如,以下属性将执行您想要的操作:
您只需将
MyAspect
作为类的属性应用,它将应用于其中的每个方法。您可以通过修改MulticastAttributeUsage
属性的TargetmemberAttributes
属性来控制应用方面的方式。在此示例中,我想将其限制为仅适用于公共非抽象方法。您还可以做更多事情,请看一下(一般来说,在 AOP 中)。
Yes, you can do this, but no, its not built in to C#. As Eric says, this technique is known as Aspect Oriented Programming.
I've used PostSharp at work, and it is very effective. It works at compile time, and uses IL-weaving, as opposed to other AOP techniques.
For example, the following attribute will do what you want:
You simply apply
MyAspect
as an attribute on your class, and it will be applied to every method within it. You can control how the aspect is applied by modifying theTargetmemberAttributes
property of theMulticastAttributeUsage
property. In this example, I want to restrict it to apply only to public, non-abstract methods.There's a lot more you can do so have a look (at AOP in general).
不,您正在寻找的是面向方面的编程(AOP)。
使用 AOP,您可以指定切入点、要编织代码的位置以及要在该点执行的代码。跟踪是 AOP 的标准示例。您指定一组方法和编织器/编译器以在该方法的开头或结尾添加日志/跟踪调用。
No. What you are looking for is aspect oriented programming (AOP).
With AOP you specify a pointcut, a place where you want to weave in code, and the code you want to executed at that point. Tracing is the standard example for AOP. You specify a set of methods and the the weaver/compiler to add you log/tracing call at the beginning or the end of that methods.