Can't operator == be applied to generic types in C#?

前端 未结 12 807
囚心锁ツ
囚心锁ツ 2020-11-22 02:21

According to the documentation of the == operator in MSDN,

For predefined value types, the equality operator (==) returns true if th

12条回答
  •  离开以前
    2020-11-22 02:36

    "...by default == behaves as described above for both predefined and user-defined reference types."

    Type T is not necessarily a reference type, so the compiler can't make that assumption.

    However, this will compile because it is more explicit:

        bool Compare(T x, T y) where T : class
        {
            return x == y;
        }
    

    Follow up to additional question, "But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?"

    I would have thought that == on the Generics would use the overloaded version, but the following test demonstrates otherwise. Interesting... I'd love to know why! If someone knows please share.

    namespace TestProject
    {
     class Program
     {
        static void Main(string[] args)
        {
            Test a = new Test();
            Test b = new Test();
    
            Console.WriteLine("Inline:");
            bool x = a == b;
            Console.WriteLine("Generic:");
            Compare(a, b);
    
        }
    
    
        static bool Compare(T x, T y) where T : class
        {
            return x == y;
        }
     }
    
     class Test
     {
        public static bool operator ==(Test a, Test b)
        {
            Console.WriteLine("Overloaded == called");
            return a.Equals(b);
        }
    
        public static bool operator !=(Test a, Test b)
        {
            Console.WriteLine("Overloaded != called");
            return a.Equals(b);
        }
      }
    }
    

    Output

    Inline: Overloaded == called

    Generic:

    Press any key to continue . . .

    Follow Up 2

    I do want to point out that changing my compare method to

        static bool Compare(T x, T y) where T : Test
        {
            return x == y;
        }
    

    causes the overloaded == operator to be called. I guess without specifying the type (as a where), the compiler can't infer that it should use the overloaded operator... though I'd think that it would have enough information to make that decision even without specifying the type.

提交回复
热议问题