在 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
方法在各种场景下都能正常工作。