要确保List<T>.Contains(T)
与您的自定义类一起使用,您需要在自定义类中重写Equals
方法和GetHashCode
方法。这样,在调用List<T>.Contains(T)
方法时,它将使用您的自定义类的这两个方法来比较对象是否相等。
以下是一个示例:
public class CustomClass
{
public int Property1 { get; set; }
public string Property2 { get; set; }
public override bool Equals(object obj)
{
if (obj is CustomClass other)
{
return this.Property1 == other.Property1 && this.Property2 == other.Property2;
}
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(this.Property1, this.Property2);
}
}
在这个示例中,我们定义了一个名为CustomClass
的自定义类,并重写了Equals
方法和GetHashCode
方法。Equals
方法用于比较两个对象是否相等,而GetHashCode
方法用于生成对象的哈希值。
现在,您可以在List<CustomClass>
中使用Contains
方法来检查是否包含特定的CustomClass
对象:
var list = new List<CustomClass>();
// 添加一些对象到列表中
list.Add(new CustomClass { Property1 = 1, Property2 = "A" });
list.Add(new CustomClass { Property1 = 2, Property2 = "B" });
list.Add(new CustomClass { Property1 = 3, Property2 = "C" });
// 检查列表中是否包含特定对象
var objToCheck = new CustomClass { Property1 = 2, Property2 = "B" };
bool contains = list.Contains(objToCheck);
在这个示例中,我们创建了一个List<CustomClass>
对象,并向其中添加了一些CustomClass
对象。然后,我们创建了一个CustomClass
对象,并检查列表中是否包含该对象。由于我们已经重写了Equals
方法和GetHashCode
方法,List<CustomClass>.Contains(CustomClass)
方法将使用这些方法来比较对象,从而确保正确的结果。
领取专属 10元无门槛券
手把手带您无忧上云