C# 运算符重载是否像 C++ 一样支持“+=”?
Does C# operator overloading support "+=" like C++?
我来自 C++,作为新手使用 C#,刚刚尝试过:
class Class1
{
int mI = 0;
string mS = "ab";
public static Class1 operator + (Class1 obj1, Class1 obj2)
{
return new Class1()
{
mI = obj1.mI + obj2.mI,
mS = obj1.mS + obj2.mS
};
}
public static void operator += (Class1 obj1)
{
mI += obj1.mI;
mS += obj1.mS;
}
}
我发现 operator+=
函数无法编译,说:
error CS1019: Overloadable unary operator expected.
所以 C# 根本不做这种运算符重载?
您可以重载 +
,但不能重载 +=
,如 per the documentation:
Assignment operators cannot be explicitly overloaded. However, when you overload a binary operator, the corresponding assignment operator, if any, is also implicitly overloaded. For example, +=
is evaluated using +
, which can be overloaded.
因此,如您所见,+=
被视为 x = x + y
。这就是为什么不允许重载 +=
运算符的原因。
我来自 C++,作为新手使用 C#,刚刚尝试过:
class Class1
{
int mI = 0;
string mS = "ab";
public static Class1 operator + (Class1 obj1, Class1 obj2)
{
return new Class1()
{
mI = obj1.mI + obj2.mI,
mS = obj1.mS + obj2.mS
};
}
public static void operator += (Class1 obj1)
{
mI += obj1.mI;
mS += obj1.mS;
}
}
我发现 operator+=
函数无法编译,说:
error CS1019: Overloadable unary operator expected.
所以 C# 根本不做这种运算符重载?
您可以重载 +
,但不能重载 +=
,如 per the documentation:
Assignment operators cannot be explicitly overloaded. However, when you overload a binary operator, the corresponding assignment operator, if any, is also implicitly overloaded. For example,
+=
is evaluated using+
, which can be overloaded.
因此,如您所见,+=
被视为 x = x + y
。这就是为什么不允许重载 +=
运算符的原因。