zoukankan      html  css  js  c++  java
  • C#不允许将操作符重载方法定义为泛型方法(转载)

    在C#中,不允许将操作符重载方法定义为泛型方法,看看下面这篇贴子:


    I am trying to implement a generic operator like so:

    class Foo
    {
       public static T operator +<T>(T a, T b) 
       {
           // Do something with a and b that makes sense for operator + here
       }
    }

    Really what I'm trying to do is gracefully handle inheritance. With a standard operator + in Foo, where T is instead "Foo", if anyone is derived from Foo (say Bar inherits Foo), then a Bar + Bar operation will still return a Foo. I was hoping to solve this with a generic operator +, but I just get a syntax error for the above (at the <) making me believe that such code is not legal.

    Is there a way to make a generic operator?


    No, you can't declare generic operators in C#.

    Operators and inheritance don't really mix well.

    If you want Foo + Foo to return a Foo and Bar + Bar to return a Bar, you will need to define one operator on each class. But, since operators are static, you won't get the benefits of polymorphism because which operator to call will be decided at compile-time:

    Foo x = new Bar();
    Foo y = new Bar();
    var z = x + y; // calls Foo.operator+;

    一个变通的方法是,我们可以将泛型参数T声明在类Foo上,而不是在操作符重载方法上:

    class Foo<T>
    {
        public static Foo<T> operator +(Foo<T> a, T b)
        {
            return a;
        }
    }

    可以参考:Arithmetic operator overloading for a generic class in C#

    原文链接:

    C# Generic Operators

  • 相关阅读:
    整理SVN代码-->正式环境的代码
    业务(1)
    在一个项目中跨领域调用接口的的实现
    一个java文件编译之后会产生多个class文件
    shutil模块
    shevle模块
    confiparser模块
    sys模块
    subprocess模块
    【ADO.NET】3、从TXT中导入数据到数据库
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/13501047.html
Copyright © 2011-2022 走看看