繁体   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