我有一个类型国家 /地区的列表,我正在尝试在列表中找到索引和特定国家 /地区的索引,但是indexof()方法总是返回-1。

乡村对象看起来像:

    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);

假设我已经有一个已经有一个国家的清单,“委内瑞拉”在列表中,索引()方法永远找不到该国。

编辑:

因此,我在这里得到了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);
            }
        }

这是另一个问题:可以比较两个对象,做所有这一切?

有帮助吗?

解决方案

我怀疑这是由于参考问题。您需要覆盖 Equals(); 您的方法 Country 课程检查。

我会使用这样的代码:

public bool Equals(Country other)
{
    return this.CountryName.Equals(other.CountryName);
}

其他提示

那是因为索引使用参考平等来比较对象

你可以使用这个

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);

或者,您可以更好地比较ovverride equals()方法来比较对象。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top