How to determine if two generic type values are equal?

前端 未结 7 2232
忘掉有多难
忘掉有多难 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

    Your code looks fine. The problem here is that StringBuilder has a confusing set of Equals that are contradictory. In particular, Equals(StringBuilder) disagrees with Equals(object), even when the object is a StringBuilder.

    All that EqualityComparer needs is a sane Equals(object) implementation. The interface (IEquatable) is optional. Unfortunately StringBuilder doesn't have this (at least, by comparison to Equals(StringBuilder), which your third test is using).

    But in general, the advice is: use EqualityComparer; this supports:

    • nullable-of-T with standard "lifted" rules
    • IEquatable-of-T
    • object.Equals

提交回复
热议问题