1

我有一个 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);
            }
        }

另一个问题来了:做这一切只是为了比较两个对象可以吗?

4

2 回答 2

1

我怀疑这是由于参考问题。您需要覆盖类中的Equals();方法以Country进行检查。

我会使用这样的代码:

public bool Equals(Country other)
{
    return this.CountryName.Equals(other.CountryName);
}
于 2011-01-24T16:36:48.077 回答
0

那是因为 IndexOf 使用引用相等来比较对象

你可以用这个

var newcountry = new Country
                 {
                     CountryCode = "VE",
                     CountryName = "VENEZUELA"
                 };


bool country = ListBoxCountries.Items.Cast<Country>().FirstOrDefault(c=>c.CountryCode == newcountry.CountryCode && c.CountryName == newcountry.CountryName)

if(country == null)
  countries.Add(newcountry);

或者您可以更好地覆盖 Equals() 方法来比较对象。

于 2011-01-24T16:35:27.830 回答