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

Bre*_*ker 3 c# operator-overloading

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

Sta*_* R. 17

您必须使用运算符重载.

public struct YourClass
{
    public int Value;

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

}
Run Code Online (Sandbox Code Playgroud)


Gre*_*ech 5

public static T operator *(T a, T b)
{
   // TODO
}
Run Code Online (Sandbox Code Playgroud)

等等其他运营商.