考虑this代码:
public static void Main()
{
var item = new Item { Id = 1 };
IList list = new List<Item> { item };
IList array = new[] { item };
var newItem = new Item { Id = 1 };
var lIndex = list.IndexOf(newItem);
var aIndex = array.IndexOf(newItem);
Console.WriteLine(lIndex);
Console.WriteLine(aIndex);
}
public class Item : IEquatable<Item>
{
public int Id { get; set; }
public bool Equals(Item other) => other != null && other.Id == Id;
}
结果:
0
-1
为什么
List<T>
和Array
的结果不同?我想这是故意的,但为什么?查看
List<T>.IndexOf
的代码让我更加好奇,因为它正在移植到Array.IndexOf
。 最佳答案
数组类调用方法中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)
方法,而不是泛型方法。在
List
类中使用泛型实现:public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
因此,它使用通用质量比较器:
EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
我写了一篇关于这个问题的帖子:http://blog.rogatnev.net/2017/07/14/IndexOf-with-IEquatable.html