为类提供运算符时,运算符实现的参数类型控制您正在处理的情况.
为了显示:
// 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)