简体   繁体   English

C#可执行属性

[英]C# Executable attributes

Is any way to define attribute like: 有没有办法定义属性,如:

public class MyAttribute : Attribute
{
    void OnFunctionInvoke() { ... }
}

And mark some function with that attribute 并使用该属性标记一些函数

[MyAttribute]
void SomeFunction() { ... }

When SomeFunction is invoked i want OnFunctionInvoke() to be invoked before. 当调用SomeFunction时,我希望之前调用OnFunctionInvoke()。

You can try using CodeAccessSecurityAttribute as a by-way : 您可以尝试使用CodeAccessSecurityAttribute 作为副产品的方法

https://msdn.microsoft.com/en-us/library/system.security.permissions.codeaccesssecurityattribute(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.security.permissions.codeaccesssecurityattribute(v=vs.110).aspx

  using System.Security.Permissions;
  ...

  [AttributeUsage(AttributeTargets.All)]
  public class MyInterceptAttribute: CodeAccessSecurityAttribute {
    public MyInterceptAttribute(SecurityAction action)
      : base(action) {
    }

    public override System.Security.IPermission CreatePermission() {
      //TODO: put relevant code here
      Console.Write("Before method execution!");

      return null;
    }
  }

  ...

  // We demand permissions which in turn leads to CreatePermission() call    
  [MyInterceptAttribute(SecurityAction.Demand)]  
  public void MyMethodUnderTest() {
    Console.Write("Method execution!");
  }

So it's, technically, possible (we exploit security), but it's a by-way only. 从技术上讲,它是可能的 (我们利用安全性),但它只是一种方式。

Natively, there's no way to do that. 在本地,没有办法做到这一点。 However, AOP frameworks like PostSharp will let you do that kind of thing. 但是,像PostSharp这样的AOP框架会让你做到这一点。

As Thomas levesque wrote, it is not possible. 正如Thomas levesque所写,这是不可能的。

Alternative you can considerate using Decorator design pattern. 另外你可以考虑使用Decorator设计模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM