返回类型为多播的委托会产生意外结果
本文关键字:意外 结果 多播 返回类型 | 更新日期: 2023-09-27 18:27:32
我试图学习委托多播,并编写了以下示例程序:
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有助于一个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