Using Attributes to Call Methods

后端 未结 3 1746
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 12:38

I have various individual methods which all need to perform the same functions before continuing on with their own implementation. Now I could implement these functions in each

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 12:51

    You can use PostSharp, it is aspect-oriented framework for .NET, it seems quite easy to use:

    static void Main(string[] args)
    {
        Foo();
    }
    
    [IgnoreMethod(IsIgnored=true)]
    public static void Foo()
    {
        Console.WriteLine("Executing Foo()...");
    }
    
    [Serializable]
    public class IgnoreMethodAttribute : PostSharp.Aspects.MethodInterceptionAspect
    {
        public bool IsIgnored { get; set; }
    
        public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args)
        {
            if (IsIgnored)
            {
                return;
            }
    
            base.OnInvoke(args);
        }
    }
    

    Method-Level Aspects feature is available in the free edition: http://www.sharpcrafters.com/purchase/compare

    Run-Time Performance:

    Because PostSharp is a compiler technology, most of the expensive work is done at build time, so that applications start quickly and execute fast. When generating code, PostSharp takes the assumption that calling a virtual method or getting a static field is an expensive operation. Contrary to rumor, PostSharp does not use System.Reflection at run time. http://www.sharpcrafters.com/postsharp/performance

提交回复
热议问题