簡體   English   中英

獲取委托方法的名稱

[英]Get name of delegate method

出於好奇,我一直在研究委托方法,並且對獲取正在使用的當前委托方法的名稱感興趣(確實很有趣)。

我的代碼如下(帶有當前/期望的輸出):

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. 是可選的,但說明它們是類成員而不是局部變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM