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

  • 相关阅读:
    正则表达式
    正则表达式-量词
    正则表达式-字符组
    6月学习总结
    利用Magick和gs实现pdf到jpg的转换
    NGS Antenna Calibrations
    VS2017运行旧版本下的C程序工程
    C#.NET SQLite自适应32位/64位系统
    RAID1环境下外挂第三块硬盘
    修复 Fontconfig Error
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/13501047.html
Copyright © 2011-2022 走看看