在 C# 中,List<T>.Contains
方法用于檢查列表中是否包含指定的元素
Contains
方法應(yīng)返回 false
。var emptyList = new List<int>();
Assert.IsFalse(emptyList.Contains(5));
Contains
方法應(yīng)返回 false
。var numbers = new List<int> { 1, 2, 3, 4 };
Assert.IsFalse(numbers.Contains(5));
Contains
方法應(yīng)返回 true
。var numbers = new List<int> { 1, 2, 3, 4 };
Assert.IsTrue(numbers.Contains(3));
Contains
方法仍然應(yīng)返回 true
。var numbers = new List<int> { 1, 2, 3, 3, 4 };
Assert.IsTrue(numbers.Contains(3));
Equals
和 GetHashCode
方法已正確實(shí)現(xiàn),以便 Contains
方法能正確地比較元素。class Person
{
public string Name { get; set; }
public override bool Equals(object obj)
{
if (obj is Person other)
{
return Name == other.Name;
}
return false;
}
public override int GetHashCode() => Name?.GetHashCode() ?? 0;
}
var persons = new List<Person>
{
new Person { Name = "Alice" },
new Person { Name = "Bob" }
};
Assert.IsTrue(persons.Contains(new Person { Name = "Alice" }));
Assert.IsFalse(persons.Contains(new Person { Name = "Charlie" }));
null
值時(shí),需要確保 Contains
方法能正確處理這種情況。var nullableInts = new List<int?> { 1, 2, null, 4 };
Assert.IsTrue(nullableInts.Contains(null));
Assert.IsFalse(nullableInts.Contains(3));
通過對(duì)這些邊界條件進(jìn)行測(cè)試,可以確保 List<T>.Contains
方法在各種場(chǎng)景下都能正常工作。