Implementing IComparable

故事扮演 提交于 2019-12-04 22:09:13

Your line:

array.Add(p1.Age = 6)

adds the result of the statement p1.Age = 6 to the ArrayList. This is the int value 6. Nothing to do with IComparable or Sort.

The best way to implement IComparable is to implement IComparable<T> and pass the calls on to that implementation:

class Person : IComparable<Person>, IComparable
{
  public int Age { get; set; }

  public int CompareTo(Person other)
  {
    // Should be a null check here...
    return this.Age.CompareTo(other.Age);
  }

  public int CompareTo(object obj)
  {
    // Should be a null check here...
    var otherPerson = obj as Person;
    if (otherPerson == null) throw new ArgumentException("...");
    // Call the generic interface's implementation:
    return CompareTo(otherPerson);
  }
}

You're not adding the Persons to the array.

p1.Age = 6

is an assignment, and it returns whatever was assigned to the variable/property (in this case, 6).

You need to do the assignments before putting the Persons into the array.

If you're only looking to put elements of a single type into a collection, you want to use a typed collection rather than an untyped one. This would have caught the problem immediately.

You are adding person.Age to your arraylist, and person.Age is an int.
You should do something like

Person p1 = new Person(){Age=3};
array.Add(p1);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!