【问题标题】:Is there a way to apply an attribute to a method that executes first?有没有办法将属性应用于首先执行的方法?
【发布时间】:2012-03-25 04:34:26
【问题描述】:

在不使用 PostSharp 之类的库的情况下,有没有一种方法可以设置一个自定义属性,当附加到一个方法时,我可以有逻辑,在进入该方法之前执行?

【问题讨论】:

    标签: c# attributes asp.net-4.0 webforms custom-attributes


    【解决方案1】:

    没有;属性不是为了注入代码。像 postsharp 这样的工具可以通过烟雾和镜子来解决这个问题,但没有那个:不。另一种选择可能是装饰器模式, 也许动态实现一个接口(无论如何都不是微不足道的)。但是,在方法的顶部添加实用方法调用要简单得多,而且可能还不错,因为如果您有权添加属性,则可以访问添加方法调用。

    或者换一种说法:postsharp 等工具的存在正是因为这不是开箱即用的。

    // poor man's aspect oriented programming
    public void Foo() {
        SomeUtility.DoSomething();
        // real code
    }
    

    在某些情况下,子类化可能很有用,特别是如果子类是在运行时完成的(元编程):

    class YouWriteThisAtRuntimeWithTypeBuilder : YourType {
        public override void Foo() {
            SomeUtility.DoSomething();
            base.Foo();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多