有没有办法将属性应用于首先执行的方法?

Bri*_*man 3 c# attributes webforms custom-attributes asp.net-4.0

如果不使用像PostSharp这样的库,有没有办法设置一个我可以拥有逻辑的自定义属性,当附加到方法时,会执行PRIOR进入该方法吗?

Mar*_*ell 5

没有; 归因不是为了注入代码.像postharp这样的工具可以用烟雾和镜子来解决这个问题,但没有这个:没有.另一个选项可能是装饰器模式,可能是动态实现一个接口(通过任何方式都不是很简单).但是,在方法的顶部添加实用程序方法调用简单得多,并且可能很好,因为如果您有权添加属性,则可以访问添加方法调用.

或者换一种方式:像postharp这样的工具存在得恰到好处,因为这不存在于开箱即用的状态.

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

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

class YouWriteThisAtRuntimeWithTypeBuilder : YourType {
    public override void Foo() {
        SomeUtility.DoSomething();
        base.Foo();
    }
}
Run Code Online (Sandbox Code Playgroud)