C# 返回类型为多播的委托会产生意外结果
我试图学习代理多播,并编写了以下示例程序:C# 返回类型为多播的委托会产生意外结果,c#,delegates,C#,Delegates,我试图学习代理多播,并编写了以下示例程序: 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 +=
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));
委托字符串strelegate(字符串str);
类strOps
{
公共静态字符串反向限制(字符串str)
{
字符串温度=字符串为空;
对于(int i=str.Length-1;i>=0;i--)
{
temp+=str[i];
}
返回温度;
}
公共字符串移除空间(字符串str)
{
字符串温度=字符串为空;
对于(int i=0;i
我希望它返回不带空格的反转字符串,相反,它只反转字符串并给出以下输出:
gnirts elpmas a 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