【发布时间】:2009-10-08 14:08:01
【问题描述】:
有人可以指出我需要实现的接口,以便让基本的数学运算符(即 +、-、*、/)在自定义类型上起作用吗?
【问题讨论】:
有人可以指出我需要实现的接口,以便让基本的数学运算符(即 +、-、*、/)在自定义类型上起作用吗?
【问题讨论】:
public struct YourClass
{
public int Value;
public static YourClass operator +(YourClass yc1, YourClass yc2)
{
return new YourClass() { Value = yc1.Value + yc2.Value };
}
}
【讨论】:
public static T operator *(T a, T b)
{
// TODO
}
其他操作员依此类推。
【讨论】:
您可以找到自定义类型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);
}
}
【讨论】:
您需要重载类型上的运算符。
// let user add matrices
public static CustomType operator +(CustomType mat1, CustomType mat2)
{
}
【讨论】:
你要找的不是界面,而是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;
【讨论】:
这是有关 C# 中的运算符和覆盖的 MSDN 文章:http://msdn.microsoft.com/en-us/library/s53ehcz3(loband).aspx
【讨论】: