Run a method before all methods of a class

前端 未结 8 2139
孤街浪徒
孤街浪徒 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:36

    I've recently had cause to do this. I'll spare you the probably boring details of my use-case, except to state that I want the method DoThisFirst to run before the specific method I'm calling. Still learning C# so probably not the best way to do it...

    using System;
    
    namespace ConsoleApp1
    {
        class Class1
        {
            public enum MethodToCall
            {
                Method2,
                Method3
            }
    
            public delegate void MyDelegate(int number = 0, bool doThis = false, double longitude = 32.11);
    
            public static void DoThisFirst(int number, bool doThis, double longitude)
            {
                Console.WriteLine("DoThisFirst has been called.");
            }
    
            public static void DoSomethingElse(int number, bool doThis, double longitude)
            {
                Console.WriteLine("DoSomethingElse has been called.");
            }
    
            public static void DoAnotherThing(int number, bool doThis, double longitude)
            {
                Console.WriteLine("DoAnotherThing has been called.");
            }
    
            public static void Main()
            {
                void Action(MethodToCall methodToCall)
                {
                    MyDelegate myDel;
    
                    myDel = new MyDelegate(DoThisFirst);
    
                    switch (methodToCall)
                    {
                        case MethodToCall.Method2:
                            myDel += DoSomethingElse;
                            break;
                        case MethodToCall.Method3:
                            myDel += DoAnotherThing;
                            break;
                    }
    
                    myDel.Invoke();
                }
    
                Action(MethodToCall.Method3);
    
                Console.ReadKey();
            }
        }
    }
    

提交回复
热议问题