C# Generic Operators

前端 未结 5 1765
心在旅途
心在旅途 2020-11-27 07:25

I am trying to implement a generic operator like so:

class Foo
{
   public static T operator +(T a, T b) 
   {
       // Do something with a and b t         


        
5条回答
  •  旧巷少年郎
    2020-11-27 07:42

    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+;
    

提交回复
热议问题