ICollection.Contains on custom types

后端 未结 4 830
旧时难觅i
旧时难觅i 2021-01-12 02:19

If I have a (reference - does it matter?) type MyType which does not override the Equals method, what heuristics will be used when determining if an IC

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 03:07

    According to MSDN:

    Implementations can vary in how they determine equality of objects; for example, List<(Of <(T>)>) uses Comparer<(Of <(T>)>)..::.Default, whereas Dictionary<(Of <(TKey, TValue>)>) allows the user to specify the IComparer<(Of <(T>)>) implementation to use for comparing keys.

    The best way to do it on your own is to use the overload that takes an IEqualityComparer

    public class MyComparer : IEqualityComparer
    {
        public bool Equals(MyType x, MyType y)
        {
            return x.Id == y.Id;
        }
    
        public int GetHashCode(MyType obj)
        {
            return obj.Id.GetHashCode();
        }
    }
    

提交回复
热议问题