gpt4 book ai didi

c# - 为什么 Array.IndexOf 不像 List 那样检查 IEquatable?

转载 作者:太空狗 更新时间:2023-10-29 20:09:25 25 4
gpt4 key购买 nike

考虑 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) 方法,而不是通用方法。

ListIndexOf 中使用通用实现:

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

关于c# - 为什么 Array.IndexOf 不像 List<T> 那样检查 IEquatable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44992402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com