How to determine if two generic type values are equal?

前端 未结 7 2205
忘掉有多难
忘掉有多难 2021-02-08 13:29

Update* I am so sorry... my sample code contained an error which resulted in a lot of answers I didn\'t understand. In stead of

Console.WriteLin         


        
7条回答
  •  不思量自难忘°
    2021-02-08 13:52

    As suggested in Marc Gravell's answer, the problem is with StringBuilder Equals(object) implementation that is different to the one in Equals(StringBuilder).

    Then, you can ignore the problem because your code will work with any other coherently-implemented classes, or you can use dynamic to fix the problem (again as suggested by Mark Gravell).

    But, given that you are not using C# 4 (so no dynamic), you can try in this way:

    public bool Equals(T value)
    {
       // uses Reflection to check if a Type-specific `Equals` exists...
       var specificEquals = typeof(T).GetMethod("Equals", new Type[] { typeof(T) });
       if (specificEquals != null &&
           specificEquals.ReturnType == typeof(bool))
       {
           return (bool)specificEquals.Invoke(this.Value, new object[]{value});
       }
       return this.Value.Equals(value);
    }
    

提交回复
热议问题