考虑this代码:为什么Array.IndexOf没有检查像List <T>这样的IEquatable呢?
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
。
我写了一篇关于这个问题的帖子:http://blog.rogatnev.net/2017/07/1 4/IndexOf-with-IEquatable.html – Backs