考慮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