gpt4 book ai didi

c# - List.Contains 奇怪的行为

转载 作者:行者123 更新时间:2023-11-30 22:31:13 24 4
gpt4 key购买 nike

我不知道我是否在这里遗漏了一些东西,但我的下面的代码总是在 List.Contains 部分引发异常并不奇怪,尽管我确信该列表包含该元素:

using System;
using System.Linq;
using System.Collections.Generic;

class SomeClass
{
public string param1 {get; private set;}
public string param2 {get; private set;}

private SomeClass(){}
public SomeClass(string param1, string param2)
{
this.param1 = param1;
this.param2 = param2;
}
}

class SomeClass2
{
private List<SomeClass> myList = new List<SomeClass>();

public void Add(SomeClass someclass)
{
myList.Add(someclass);
}

public void Remove(SomeClass someClass)
{
// this part always rises an exception
if(!myList.Contains(someClass))
throw new System.ArgumentException("some error");
else myList.Remove(someClass);
}
}

class MainClass
{
public static void Main (string[] args)
{
var _someClass = new SomeClass2();
_someClass.Add(new SomeClass("aaa", "bbb"));

try
{
_someClass.Remove(new SomeClass("aaa", "bbb"));
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}

最佳答案

引自documentationContains方法:

This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable(Of T).Equals method for T (the type of values in the list).

所以你可以实现 IEquatable<T> 如果您希望 Contains 方法确定是否有 2 个 SomeClass 实例,请在您的对象上相等:

class SomeClass: IEquatable<SomeClass>
{
public string param1 { get; private set; }
public string param2 { get; private set; }

private SomeClass() { }
public SomeClass(string param1, string param2)
{
this.param1 = param1;
this.param2 = param2;
}

public bool Equals(SomeClass other)
{
return param1 == other.param1 && param2 == other.param2;
}
}

另一种可能性是实现自定义 EqualityComparer<T> :

class SomeClassEqualityComparer : IEqualityComparer<SomeClass>
{
private static readonly SomeClassEqualityComparer _instance = new SomeClassEqualityComparer();

public bool Equals(SomeClass x, SomeClass y)
{
return x.param1 == y.param1 && x.param2 == y.param2;
}

public int GetHashCode(SomeClass obj)
{
unchecked
{
int hash = 17;
hash = hash * 23 + obj.param1.GetHashCode();
hash = hash * 23 + obj.param2.GetHashCode();
return hash;
}
}

public static IEqualityComparer<SomeClass> Instance
{
get { return _instance; }
}
}

然后使用 Contains 方法的以下重载:

if (!myList.Contains(someClass, SomeClassEqualityComparer.Instance))
throw new System.ArgumentException("some error");

关于c# - List.Contains 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9349243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com