Creating a delegate type inside a method

2020-02-23 07:36发布

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

For example:

public void MyMethod(){
   delegate int Sum(int a, int b);

   Sum mySumImplementation=delegate (int a, int b) {return a+b;}

   Console.WriteLine(mySumImplementation(1,1).ToString());
}

Unfortunately, I cannot do it using .NET 2.0 and C# 2.0.

4条回答
Deceive 欺骗
2楼-- · 2020-02-23 07:59

Delegates are compiled to classes(a class that inherits from System.MulticastDelegate). In C#, you are not allowed to declare a class inside a method(see C# language specification). Thus you can't declare a delegate in a method, either.

查看更多
小情绪 Triste *
3楼-- · 2020-02-23 08:07

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<int, int, int> mySumImplementation = 
        delegate (int a, int b) { return a+b; };

    Console.WriteLine(mySumImplementation(1,1).ToString());
}

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

查看更多
Fickle 薄情
4楼-- · 2020-02-23 08:08

What about this:

static void Main(string[] args)
{
    Expression<Func<int, int, int>> exFunc = (a, b) => a + b;
    var lambda = exFunc as LambdaExpression;
    Delegate del = exFunc.Compile();
    Console.WriteLine(del.DynamicInvoke(2, 2));
}
查看更多
戒情不戒烟
5楼-- · 2020-02-23 08:12

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<R>();
delegate R Func<T, R>(T t);
delegate R Func<T0, T1, R>(T0 t0, T1 t1);
delegate R Func<T0, T1, T2, R>(T0 t0, T1 t1, T2 t2);

Then you can just use a Func<int, int, int> delegate in your code above.

查看更多
登录 后发表回答