下面的代碼工作正常(無conpiler錯誤,這意味着代碼沒有錯誤)如何將+ =與對象一起使用?
//....
public static void CreatePingers(int kt)
{
for (int start = 1; start <= kt; start++)
{
//class System.Net.NetworkInformation.Ping
Ping p = new Ping();
//This code working fine, But it mean use += for object type?
p.PingCompleted += Ping_completed();
pingers.Add(p);
}
}
public static PingCompletedEventHandler Ping_completed()
{
PingCompletedEventHandler a = new PingCompletedEventHandler(abc);
return a;
}
//....
但我的測試代碼不起作用:
//....
static void setB()
{
Class3 b = new Class3();
//Error"Operator '+=' cannot be applied to operands of type 'Class2' and 'Class2'
b.B += a();
}
public static Class2 a()
{
Class2 b = new Class2();
return b;
}
//....
它們之間有什麼向度?
參見[事件教程(HTTPS ://msdn.microsoft.com/library/aa645739.aspx),特別是關於「連接到事件」的部分。 - 另外,'first + = second;'是'first = first + second;'的語法糖。如果需要,您可以[重載](https://msdn.microsoft.com/library/8edha89s.aspx)類中的「+」運算符。 – Corak