How to determine if two generic type values are equal?

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

    You can either implement IEquatable, or implement a comparer class that implements IEqualityComparer.

    Make sure that value you check for equality is immutable and is set only at initialization of the class.

    Another consideration would be to implement IComparer, when you implement this one, you don't have to worry about the hash-code, and thus, can be implemented for mutable types/fields as well.

    Once you'll properly implement IEquatable in your class, your questions will be solved.

    Update: Calling return EqualityComparer.Default.Equals(Value, value); would basically return same result since there is no IEqualityComparer implemented...

提交回复
热议问题