覆盖运算符c#

gru*_*ber 2 c# .net-4.0

我想为我的班级覆盖operator*.我知道如何处理MyClass*MyClass的*但是我如何实现这个以便有可能乘以例如:

7*MyClass

7是让我们说双重和MyClass是MyClass的对象,

感谢帮助

Bev*_*van 8

为类提供运算符时,运算符实现的参数类型控制您正在处理的情况.

为了显示:

// Declare which operator to overload (+), the types 
// that can be added (two Complex objects), and the 
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2) 
{
   return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
Run Code Online (Sandbox Code Playgroud)

此方法定义了如果要添加两个Complex数字,该怎么做.

如果您尝试将此与(例如)a double和a一起使用Complex,则编译将失败.

在您的情况下,您只需要声明两个版本:

public static MyClass operator *(MyClass c1, MyClass c2) 
{
   return ...
}

public static MyClass operator *(double n, MyClass c) 
{
   return ...
}
Run Code Online (Sandbox Code Playgroud)

  • 另请注意,7*MyClass与MyClass*7不同.您需要两个运算符重载才能实现这一点. (3认同)