List.Contains is not working as hoped

前端 未结 4 1137
[愿得一人]
[愿得一人] 2020-12-06 08:28

If I have an object of type MyBull and a List orig:

// Just an example
MyBull x = getMeTheObjectWithIdFromDB(9);

ori         


        
4条回答
  •  天命终不由人
    2020-12-06 09:04

    This is because the MyBull instances are being compared by reference. From the point of view from .NET, x and y are both different instances and therefore not Equal.

    In order to get around this you will have to override the Equals and GetHashCode methods (which means you should probably implement IEquatable and override the == and != operators too).

提交回复
热议问题