[英]How list<T> to check whether contains a custom struct?
我有以下实现
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// item.Equals().
//
public bool Contains(T item) {
if ((Object) item == null) {
for(int i=0; i<_size; i++)
if ((Object) _items[i] == null)
return true;
return false;
}
else {
EqualityComparer<T> c = EqualityComparer<T>.Default;
for(int i=0; i<_size; i++) {
if (c.Equals(_items[i], item)) return true;
}
return false;
}
}
如果item
是struct
值类型,那么流程if
进入if
块而不是else
块? 我对此实现感到困惑。
谁能向我解释Contains
方法如何评估像struct
这样的值类型?
if
部分仅检查我们是否在列表中寻找null
项目。 如果这样做,它将遍历列表,并在列表项中查找null
值。 这部分仅对引用类型有效,因为值类型不能为null
。
在else
另一方面的一部分,是做的所有检查的情况下,当产品不能null
,所以这段代码被用于structs
为好。 它所做的是为该类型( EqualityComparer<T> c = EqualityComparer<T>.Default
)获得一个默认的相等比较器,并使用此比较器在列表中查找项目。
您需要了解的是value type
和reference type
之间的区别。
就像int
, long
等一样, struct
不是存储在heap
而是存储在stack
。 reference type
在stack
上存储了一个指向实际对象数据的指针(这是一个内存地址),该stack
存储在heap
。
(继续阅读有关堆栈和堆之间的区别。)
然而,加入了struct
的东西像一个ArrayList
甚至List<object>
仍然会起作用,因为它极有可能被装箱为reference type
第一,因此struct
西港岛线不能 null
,即使你通过了default(<struct type>)
它仍然不会为 null
。
然后,就像@dotnetom解释的else
部分一样,执行并评估struct
是否在集合中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.