实施IndexOf
在数组类中调用方法:
public static int IndexOf(Array array, object value, int startIndex, int count)
如您所见,它使用object
作为值参数。该方法中有代码:
object obj = objArray[index];
if (obj != null && obj.Equals(value))
return index;
类与对象一起工作,因此它调用public virtual bool Equals(object obj)
方法,而不是通用方法。
In List
class IndexOf
使用通用实现:
public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
因此,它使用通用质量比较器:
EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
UPD: 我写了一篇关于这个问题的小文章:http://blog.rogatnev.net/2017/07/14/IndexOf-with-IEquatable.html http://blog.rogatnev.net/2017/07/14/IndexOf-with-IEquatable.html