Shi*_*mmy 8 .net c# collections indexof 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;
}
Run Code Online (Sandbox Code Playgroud)
结果:
0
-1
Run Code Online (Sandbox Code Playgroud)
为什么结果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;
Run Code Online (Sandbox Code Playgroud)
类与对象一起使用,因此它调用public virtual bool Equals(object obj)方法,而不是泛型方法。
在List课堂上IndexOf使用通用实现:
public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
Run Code Online (Sandbox Code Playgroud)
因此,它使用通用质量比较器:
EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
Run Code Online (Sandbox Code Playgroud)
UPD:我写了一篇有关此问题的文章:http : //blog.rogatnev.net/2017/07/14/IndexOf-with-IEquatable.html
| 归档时间: |
|
| 查看次数: |
344 次 |
| 最近记录: |