Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Executable attributes

Tags:

c#

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.

like image 275
igorr Avatar asked Aug 27 '26 13:08

igorr


1 Answers

You can try using CodeAccessSecurityAttribute as a by-way:

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.

like image 107
Dmitry Bychenko Avatar answered Aug 29 '26 03:08

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!