Creating a delegate type inside a method

后端 未结 4 1406
轻奢々
轻奢々 2020-12-29 05:38

I want to create a delegate type in C# inside a method for the purpose of creating Anonymous methods.

For example:

public void MyMethod(){
   delegat         


        
4条回答
  •  伪装坚强ぢ
    2020-12-29 06:02

    The delegate type has to be defined outside the function. The actual delegate can be created inside the method as you do.

    class MyClass {
      delegate int Sum(int a, int b);
      public void MyMethod(){
    
           Sum mySumImplementation=delegate (int a, int b) {return a+b;}
    
           Console.WriteLine(mySumImplementation(1,1).ToString());
      }
    
    }
    

    would be valid. The best solution may be to emulate .NET3.5, and create some generic delegate types globally, which can be used all over your solution, to avoid having to constantly redeclare delegate types for everything:

    delegate R Func();
    delegate R Func(T t);
    delegate R Func(T0 t0, T1 t1);
    delegate R Func(T0 t0, T1 t1, T2 t2);
    

    Then you can just use a Func delegate in your code above.

提交回复
热议问题