2009-10-08 5 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

В общем , если вы выполняете перегрузку оператора, вы, вероятно, имеете дело с типом значения, а не ссылочным типом, который должен (потенциально) быть базовым классом для других типов, поэтому вам следует рассмотреть возможность использования структуры, а не класса для лежащий в основе Тип. –

+0

Чарльз, спасибо за это предложение, я упустил это. Я редактировал код. –

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; 
Смежные вопросы