开发者

.NET Attribute Class Plugging

开发者 https://www.devze.com 2023-01-24 15:25 出处:网络
Is there any way to write a custom class which extends .NET Attribute class so that I can apply that class on a method and .NET Framew开发者_运维知识库ork calls my class constructor before executing t

Is there any way to write a custom class which extends .NET Attribute class so that I can apply that class on a method and .NET Framew开发者_运维知识库ork calls my class constructor before executing that method. Here is the example

public class TestAttribute : Attribute
{
    public TestAttribute()
    {
        Console.WriteLine("Called");
    }
}

class Program
{
    static void Main(string[] args)
    {
        TestMethod();
    }

    [TestAttribute()]
    public static void TestMethod()
    {

    }

}

I want when TestMethod is called, framework will execute TestAttribute() constructor.


In regular .NET attributes don't cause magic invocation, except for a very limited set of system attributes (security etc). The rest are applied only by inspection through reflection, which has to be done explicitly.

You might look at PostSharp (now renamed into a commercial product).


I don't believe so - Attributes are only read by things reflecting over the code, they aren't called during normal execution.


Yes it is possible, but not as is.

You can do that by using Aspect Oriented Programming. PostSharp is a framework that allows you to do that; it allows you to 'weave' aspects into the code at compile time.

Postsharp

[Serializable]
public class TestAttribute : OnMethodInvocationAspect
{
   public override void OnInvocation()
   {
       Console.WriteLine ("TestAttribute called");
       base.OnInvocation();
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消