Run a method before all methods of a class

前端 未结 8 2122
孤街浪徒
孤街浪徒 2020-12-06 15:51

Is it possible to do that in C# 3 or 4? Maybe with some reflection?

class Magic
{

    [RunBeforeAll]
    public void BaseMethod()
    {
    }

    //runs Ba         


        
8条回答
  •  执念已碎
    2020-12-06 16:47

    Use https://github.com/Fody/Fody . The licencing model is based on voluntary contributions making it the better option to PostSharp which is a bit expensive for my taste.

    [module: Interceptor]
    namespace GenericLogging
    {
    
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module)]
        public class InterceptorAttribute : Attribute, IMethodDecorator
        {
            // instance, method and args can be captured here and stored in attribute instance fields
            // for future usage in OnEntry/OnExit/OnException
            public void Init(object instance, MethodBase method, object[] args)
            {
                Console.WriteLine(string.Format("Init: {0} [{1}]", method.DeclaringType.FullName + "." + method.Name, args.Length));
            }
    
            public void OnEntry()
            {
                Console.WriteLine("OnEntry");
            }
    
            public void OnExit()
            {
                Console.WriteLine("OnExit");
            }
    
            public void OnException(Exception exception)
            {
                Console.WriteLine(string.Format("OnException: {0}: {1}", exception.GetType(), exception.Message));
            }
        }
    
        public class Sample
        {
            [Interceptor]
            public void Method(int test)
            {
                Console.WriteLine("Your Code");
            }
        }
    }
    
    [TestMethod]
    public void TestMethod2()
    {
        Sample t = new Sample();
        t.Method(1);
    }
    

提交回复
热议问题