在自定义C#类型中实现数学函数?

时间:2009-10-08 14:08:02

标签: c# operator-overloading

有人能指出我需要实现的接口,以便让基本的数学运算符(即+, - ,*,/)在自定义类型上运行吗?

6 个答案:

答案 0 :(得分: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 };
   }

}

答案 1 :(得分:5)

public static T operator *(T a, T b)
{
   // TODO
}

等其他运营商。

答案 2 :(得分: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);
   }
}

答案 3 :(得分:2)

您需要重载类型上的运算符。

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

答案 4 :(得分: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;

答案 5 :(得分:1)

以下是有关运算符和覆盖C#的MSDN文章:http://msdn.microsoft.com/en-us/library/s53ehcz3(loband).aspx