[英]Delegates with return type multicast gives unexpected result
I was trying to learn delegate multicasting and wrote this sample program : 我试图学习委托多播并编写了此示例程序:
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));
I expected it to return the reversed string without spaces , instead it ONLY reverses string and gives this output : gnirts elpmas a si sihT 我期望它返回没有空格的反向字符串,相反,它仅反向字符串并给出以下输出:gnirts elpmas si sihT
Can anybody please point me in the right direction to understand this. 有人能指出我正确的方向来理解这一点吗? Any help will be appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。
A combined delegate will only return the result of the last invoked method . 组合的委托将仅返回最后调用的方法的结果。 From the documentation : 从文档中 :
If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked 如果委托具有返回值和/或out参数,则它将返回最后调用的方法的返回值和参数
The multicast delegate will still invoke both methods assigned to it . 多播委托仍将调用分配给它的两个方法 。 If you change your methods to print the value before returning it, you'll see it clearly: 如果您更改方法以在返回值之前打印该值,您将清楚地看到它:
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;
}
}
Outputs: 输出:
Output from RemoveSpaces: Thisisasamplestring
Output from ReverseString: gnirts elpmas a si sihT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.