先来看看下面的这段代码
02 | using System.Collections.Generic; |
06 | namespace ConsoleApplication1 |
10 | public int Width { get ; set ; } |
11 | public int Height { get ; set ; } |
12 | public Shape( int width, int height) |
21 | public static Shape operator +(Shape shap1, Shape shape2) |
23 | Shape temp = new Shape(); |
24 | temp.Width = shap1.Width + shape2.Width; |
25 | temp.Height = shape2.Height + shap1.Height; |
32 | static void Main( string [] args) |
34 | Shape shape1 = new Shape(1, 1); |
35 | Shape shape2 = new Shape(2, 2); |
36 | Shape shape = shape1 + shape2; |
37 | Console.WriteLine(shape.Width); |
38 | Console.WriteLine(shape.Height); |
[info]
输出:
3
3
[/info]
还是上面这段代码,如果我们改变一个运算符重载那块代码的位置,变成如下:
02 | using System.Collections.Generic; |
06 | namespace ConsoleApplication1 |
10 | public int Width { get ; set ; } |
11 | public int Height { get ; set ; } |
12 | public Shape( int width, int height) |
26 | public static Shape operator +(Shape shap1, Shape shape2) |
28 | Shape temp = new Shape(); |
29 | temp.Width = shap1.Width + shape2.Width; |
30 | temp.Height = shape2.Height + shap1.Height; |
33 | static void Main( string [] args) |
35 | Shape shape1 = new Shape(1, 1); |
36 | Shape shape2 = new Shape(2, 2); |
37 | Shape shape = shape1 + shape2; |
38 | Console.WriteLine(shape.Width); |
39 | Console.WriteLine(shape.Height); |
[info]这个时候,我们重新运行这段代码,便会报“二元运算符的参数之一必须是包含类型”的错误[/info]
导致报二元运算符的参数之一必须是包含类型错误的原因有哪些
(1)就是跟我们的上面代码类似的情况,两个参数都是Shape类型,但是由于重载代码的位置放的不正确,就导致这个错误
(2)就是运算符重载的地方,所有的参数都不是重载返回的类型。比如我们Shape类型,那么你的参数里面至少有一个必须是Shape类型的参数
转自:http://www.iamlisen.com/c-is-one-of-the-parameters-of-a-binary-operator-must-be-the-containing-type.html