下面的代码工作正常(无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