簡體   English   中英

具有返回類型多播的代表給出了意外結果

[英]Delegates with return type multicast gives unexpected result

我試圖學習委托多播並編寫了此示例程序:

delegate string strDelegate(string str);

class strOps
{
    public static string reverseString(string str)
    {
        string temp = string.Empty;
        for(int i=str.Length -1 ; i>=0 ; i--)
        {
            temp += str[i];
        }

        return temp;

    }

    public string removeSpaces(string str)
    {
        string temp = string.Empty;
        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] != ' ')
                temp += str[i];
        }

        return temp;
    }
}

// calling the code in main method
string str = "This is a sample string";
strOps obj = new strOps();
strDelegate delRef = obj.removeSpaces;
delRef += strOps.reverseString;

Console.WriteLine("the result of passing This is a sample string  \n {0}", delRef(str));

我期望它返回沒有空格的反向字符串,相反,它僅反向字符串並給出以下輸出:gnirts elpmas si sihT

有人能指出我正確的方向來理解這一點嗎? 任何幫助將不勝感激。 謝謝。

組合的委托將僅返回最后調用的方法的結果。 從文檔中

如果委托具有返回值和/或out參數,則它將返回最后調用的方法的返回值和參數

多播委托仍將調用分配給它的兩個方法 如果您更改方法以在返回值之前打印該值,您將清楚地看到它:

void Main()
{
    string str = "This is a sample string";
    strOps obj = new strOps();
    strDelegate delRef = obj.removeSpaces;
    delRef += strOps.reverseString;

    delRef(str);
}

delegate string strDelegate(string str); 
class strOps
{
    public static string reverseString(string str)
    {
        string temp = string.Empty;
        for(int i=str.Length -1 ; i>=0 ; i--)
        {
            temp += str[i];
        }
        Console.WriteLine("Output from ReverseString: {0}", temp);
        return temp;

    }

    public string removeSpaces(string str)
    {
        string temp = string.Empty;
        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] != ' ')
                temp += str[i];
        }
        Console.WriteLine("Output from RemoveSpaces: {0}", temp);
        return temp;
    }
}

輸出:

Output from RemoveSpaces: Thisisasamplestring
Output from ReverseString: gnirts elpmas a si sihT

暫無
暫無

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

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