C#属性修改方法 [英] C# Attribute to modify methods

查看:505
本文介绍了C#属性修改方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有。也许我没有足够的一派,但我不能找到这个问题的例子。

all. Maybe i've not googled enough, but i can't find any example on this question.

这是在C#中可以创建当中,应用到一个自定义属性类,修改其所有的方法呢?例如,增加了 Console.WriteLine(你好,我是修正法); 作为第一行(或者它相当于IL如果它在运行时完成)

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

推荐答案

是的,你可以这样做,但没有,它没有内置于C#。埃里克说,这种技术被称为面向方面编程。

Yes, you can do this, but no, its not built in to C#. As Eric says, this technique is known as Aspect Oriented Programming.

我用 PostSharp 的工作,这是非常有效的。它的工作原理在编译的时候,并使用IL-织造,而不是其他AOP技术

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:

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method | MulticastTargets.Class,
                         AllowMultiple = true,
                         TargetMemberAttributes = MulticastAttributes.Public | 
                                                  MulticastAttributes.NonAbstract | 
                                                  MulticastAttributes.Managed)]
class MyAspect : OnMethodInvocationAspect
{
    public override void OnInvocation(MethodInvocationEventArgs eventArgs)
    {
        Console.WriteLine("Hello, i'm modified method");

        base.OnInvocation(eventArgs);
    }
}

您简单地套用 MyAspect 作为类的属性,它会被应用到内它的每一个方法。您可以控制的方面是通过修改 MulticastAttributeUsage 属性的 TargetmemberAttributes 属性的应用。在这个例子中,我想限制为只适用于公共,非抽象的方法。

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 the TargetmemberAttributes property of the MulticastAttributeUsage property. In this example, I want to restrict it to apply only to public, non-abstract methods.

有很多更你可以这样做在看(在AOP一般)。

There's a lot more you can do so have a look (at AOP in general).

这篇关于C#属性修改方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆