class MyNumber
{
public int Number { get; set; }
}
我不明白为什么下面的代码会抛出错误。
class Program
{
public static void Main()
{
MyNumber firstNumber = new MyNumber();
MyNumber secondNumber = new MyNumber();
firstNumber.Number = 10;
secondNumber.Number = 5;
MyNumber sum = firstNumber + secondNumber;
}
}
答案 0 :(得分:4)
目前没有为MyNumber定义+
运算符,这意味着当您尝试使用它时会出现语法错误,而您可能需要这样的内容:
class MyNumber
{
public int Number { get; set; }
public static MyNumber operator +(MyNumber c1, MyNumber c2)
{
//sum the .Number components and return them as a new MyNumber
return new MyNumber{ Number = c1.Number + c2.Number };
}
}
这样做可以解释{My}类
中的+
意味着什么
答案 1 :(得分:4)
这些加法运算符中的每一个都会根据其使用的类型产生不同的结果。
string s = "Foo" + "Bar"; //Resulting in FooBar
int i = 1 + 3; //Resulting in 4
现在,对于您的自定义类,如果您不告诉它该怎么做,您希望操作员如何运作?
答案 2 :(得分:0)
答案非常简单,编译器不知道如何处理自定义类型的操作
你引用的例子很简单,你想要,当我说添加+
然后添加具有相同名称的属性时,让我们再举一个例子乘法*
作为你已经研究过的基本复数类我们知道复数类的乘法是,
(a + i b)*(c + i d)= ac -bd + i (bc + ad)
你认为编译器有一个神奇的技巧,他知道这是一个复杂的数字类,乘法就像这样进行,当然它不知道你需要告诉它你必须进行操作, 这就是为什么需要运算符重载,当然如果你不重载,你会在错误列表中说明异常
错误1运算符'+'无法应用于'ConsoleApplicationTest.Class1'和'ConsoleApplicationTest.Class1'类型的操作数
因此对于复杂的类实现将是这样的,
public class Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator *(Complex c1, Complex c2)
{
return new Complex(c1.real * c2.real - c1.imaginary * c2.imaginary, c1.imaginary * c2.real + c1.real * c2.imaginary);
}
}