获取委托方法的名称

本文关键字:方法 获取 | 更新日期: 2023-09-27 18:07:26

出于好奇,我一直在研究委托方法,我对获得正在使用的当前委托方法的名称很感兴趣(只是为了好玩,真的)。

我的代码如下(带有当前/期望的输出):

private delegate int mathDelegate(int x, int y);
public static void Main()
{
    mathDelegate add = (x,y) => x + y;
    mathDelegate subtract = (x,y) => x - y;
    mathDelegate multiply = (x,y) => x * y;
    var functions = new mathDelegate[]{add, subtract, multiply};
    foreach (var function in functions){
        var x = 6;
        var y = 3;
        Console.WriteLine(String.Format("{0}({1},{2}) = {3}", function.Method.Name, x, y, function(x, y)));
    }
}
        /// Output is:
        // <Main>b__0(6,3) = 9
        // <Main>b__1(6,3) = 3
        // <Main>b__2(6,3) = 18
        /// Desired output
        // add(6,3) = 9
        // subtract(6,3) = 3
        // multiply(6,3) = 18

有谁知道我有什么方法可以做到这一点吗?谢谢。

获取委托方法的名称

你的方法是匿名委托,所以编译器给每个方法一个名字,这个名字和变量名没有任何有意义的联系。如果你想让它们有更好的名字,那就把它们变成实际的方法:

public int Add(int x, int y)
{ 
   return x + y ;
}

等。然后通过名称引用它们:

var functions = new mathDelegate[]{this.Add, this.Subtract, this.Multiply};

注意,this.是可选的,但说明它们是类成员而不是局部变量。