2009-10-08 46 views

回答

17

你必須使用operator overloading.

public struct YourClass 
{ 
    public int Value; 

    public static YourClass operator +(YourClass yc1, YourClass yc2) 
    { 
     return new YourClass() { Value = yc1.Value + yc2.Value }; 
    } 

} 
+0

一般,如果你正在做運算符重載,你可能正在處理什麼是值類型而不是需要(可能)成爲其他類型的基類的引用類型,所以你應該考慮使用一個結構而不是一個類來基礎類型。 – 2009-10-08 14:22:27

+0

查爾斯,謝謝你的建議,我忽略了它。我編輯了代碼。 – 2009-10-08 14:26:14

2

您需要重載該類型的運算符。

// let user add matrices 
    public static CustomType operator +(CustomType mat1, CustomType mat2) 
    { 
    } 
3

你可以找到操作的重載自定義類型here一個很好的例子。

public struct Complex 
{ 
    public int real; 
    public int imaginary; 

    public Complex(int real, int imaginary) 
    { 
     this.real = real; 
     this.imaginary = imaginary; 
    } 

    // 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); 
    } 
} 
5
public static T operator *(T a, T b) 
{ 
    // TODO 
} 

等了其他運營商。

2

你正在尋找的不是一個接口,而是Operator Overloading。一起

public static MyClass operator+(MyClass first, MyClass second) 
{ 
    // This is where you combine first and second into a meaningful value. 
} 

之後,您可以添加MyClasses:基本上,你定義一個靜態方法,像這樣

MyClass first = new MyClass(); 
MyClass second = new MyClass(); 
MyClass result = first + second;