Run a method before all methods of a class

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

    There is an alternate solution for this, make Magic a singleton and put your code on the getter of the static instance. That's what i did.

    public class Magic{
    
    private static Magic magic;
    public static Magic Instance{
      get
        {
       BaseMethod();
        return magic;
        }
    }
    
    public void BaseMethod(){
    }
    
    //runs BaseMethod before being executed
    public void Method1(){
    }
    
    //runs BaseMethod before being executed
    public void Method2(){
    }
    }
    

提交回复
热议问题