我有一个 Country 类型的项目列表,我试图在列表中找到特定 Country 的索引,但 IndexOf() 方法总是返回-1。
Country 对象如下所示:
public class Country
{
public string CountryCode { get; set; }
public string CountryName { get; set; }
}
然后,当我尝试使用 IndexOf() 方法时,我会执行以下操作:
var newcountry = new Country
{
CountryCode = "VE",
CountryName = "VENEZUELA"
};
var countries = ListBoxCountries.Items.Cast<Country>().ToList();
if (countries.IndexOf(newcountry) == -1)
countries.Add(newcountry);
假设我有一个已填写的国家/地区列表,并且“委内瑞拉”在列表中,IndexOf() 方法永远找不到该国家/地区。
编辑:
所以我在这里得到了 ReSharper 的一些帮助,一旦我告诉他重写 Equals() 方法,他就做到了:
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Country)) return false;
return Equals((Country) obj);
}
public bool Equals(Country other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.CountryCode, CountryCode) && Equals(other.CountryName, CountryName);
}
public override int GetHashCode()
{
unchecked
{
return ((CountryCode != null ? CountryCode.GetHashCode() : 0)*397) ^ (CountryName != null ? CountryName.GetHashCode() : 0);
}
}
另一个问题来了:做这一切只是为了比较两个对象可以吗?