【问题标题】:Implement math functions in custom C# type?在自定义 C# 类型中实现数学函数?
【发布时间】:2009-10-08 14:08:01
【问题描述】:

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

【问题讨论】:

    标签: c# operator-overloading


    【解决方案1】:

    你必须使用operator overloading.

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

    【讨论】:

    • 一般来说,如果您正在执行运算符重载,您可能正在处理需要(可能)成为其他类型的基类的值类型而不是引用类型,所以您应该考虑为底层 Type 使用结构而不是类。
    • Charles,感谢我忽略了它的建议。我编辑了代码。
    【解决方案2】:
    public static T operator *(T a, T b)
    {
       // TODO
    }
    

    其他操作员依此类推。

    【讨论】:

      【解决方案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);
         }
      }
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          你要找的不是界面,而是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;
          

          【讨论】:

            【解决方案6】:

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

            【讨论】:

              猜你喜欢
              • 2023-03-25
              • 1970-01-01
              • 2021-05-12
              • 1970-01-01
              • 2020-05-10
              • 2012-03-12
              • 2020-03-13
              • 2022-12-14
              • 1970-01-01
              相关资源
              最近更新 更多