出于好奇,我一直在研究委托方法,并对获取当前正在使用的委托方法的名称感兴趣(只是为了好玩,真的)。
我的代码如下(具有当前/期望的输出):
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有人知道我有什么办法能做到这一点吗?谢谢。
发布于 2015-08-11 20:02:03
您的方法是匿名委托,因此编译器为每个方法都提供了一个名称,该名称与变量名没有任何有意义的连接。如果您希望它们有更好的名称,那么就让它们具有实际的方法:
public int Add(int x, int y)
{
return x + y ;
}等等。然后用名字引用它们:
var functions = new mathDelegate[]{this.Add, this.Subtract, this.Multiply};注意,this.是可选的,但说明它们是类成员而不是局部变量。
https://stackoverflow.com/questions/31950832
复制相似问题