C# Generic Operators

前端 未结 5 1764
心在旅途
心在旅途 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 08:00

    You cannot declare generic operators in C# - I am not sure on the reasoning but assume it's a usefulness vs effort thing for the implementation team (I believe there might be a post on here with Jon Skeet discussing it, or perhaps on his blog when he discussed things he'd like to see in C#).

    Indeed, you cannot even use operators with generics in C#.

    This is because generics must be applicable for all possible types that could be provided. This is why you must scope the generic type to classes when you want to use == as below:

    void IsEqual(T x, T y) where T : class
    {
        return x == y;
    }
    

    Unfortunately you cannot do:

    void Add(T x, T y)  where T : operator +
    {
        return x + y;
    }
    

    You might also be interested in this short summary article I came across.

提交回复
热议问题