首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何确保List <T> .Contains(T)与我的自定义类一起使用?

要确保List<T>.Contains(T)与您的自定义类一起使用,您需要在自定义类中重写Equals方法和GetHashCode方法。这样,在调用List<T>.Contains(T)方法时,它将使用您的自定义类的这两个方法来比较对象是否相等。

以下是一个示例:

代码语言:csharp
复制
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对象:

代码语言:csharp
复制
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)方法将使用这些方法来比较对象,从而确保正确的结果。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券