Creating a delegate type inside a method

后端 未结 4 1438
轻奢々
轻奢々 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:08

    Why do you want to create the delegate type within the method? What's wrong with declaring it outside the method? Basically, you can't do this - you can't declare a type (any kind of type) within a method.

    One alternative would be to declare all the Func/Action generic delegates which are present in .NET 3.5 - then you could just do:

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

    The declarations are on my C#/.NET Versions page.

提交回复
热议问题