在 C# 中,List<T>.Contains
方法用于檢查列表中是否包含指定的元素
Contains
方法應返回 false
。var emptyList = new List<int>();
Assert.IsFalse(emptyList.Contains(5));
Contains
方法應返回 false
。var numbers = new List<int> { 1, 2, 3, 4 };
Assert.IsFalse(numbers.Contains(5));
Contains
方法應返回 true
。var numbers = new List<int> { 1, 2, 3, 4 };
Assert.IsTrue(numbers.Contains(3));
Contains
方法仍然應返回 true
。var numbers = new List<int> { 1, 2, 3, 3, 4 };
Assert.IsTrue(numbers.Contains(3));
Equals
和 GetHashCode
方法已正確實現,以便 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
值時,需要確保 Contains
方法能正確處理這種情況。var nullableInts = new List<int?> { 1, 2, null, 4 };
Assert.IsTrue(nullableInts.Contains(null));
Assert.IsFalse(nullableInts.Contains(3));
通過對這些邊界條件進行測試,可以確保 List<T>.Contains
方法在各種場景下都能正常工作。