سؤال

I am using IComparable and a IComparer

In the Student class:[IComparable]

    public int CompareTo(Student studentToCompare)
    {
        if (this.Number < studentToCompare.Number)
            return 1;
        else if (this.Number > studentToCompare.Number)
            return -1;
        else
            return 0;
    }

In the StudentCompareName class: [IComparer]

    public int Compare(Student x, Student y)
    {
        return string.Compare(x.Name, y.Name);
    }

With Compare(Student x, Student y) I am sorting the list of students on name.

If I dont use a CompareTo() in the Student-class, I'm getting errors.

I wonder why I need to have a CompareTo() in my main (Student) class, and what does it do? Why do I need to compare first the student number in the Student class and after that I'm allowed to sort on name in the StudentCompareName class?

هل كانت مفيدة؟

المحلول

I am using IComparable and a IComparer

That's the source of the confusion. You only need one of the two - and they'd rarely be implemented in the same class.

IComparable<T> is implemented to give a natural comparison between one object and another. In the case of something like Student, that probably doesn't make sense, as there are multiple ways to compare students. On the other hand, for something like DateTime it makes perfect sense.

IComparer<T> is meant to be a custom comparison - so it makes sense to have a StudentNameComparer which implements IComparer<Student> by comparing the names, for example.

نصائح أخرى

IComparable is an interface, meaning it defines methods that must be implemented in your inheriting class. It's simply your implementation of what "Compare" means to your object(s).

CompareTo defines whether your base student is "greater than", "less than", or "equal to" your studentToCompare, and you can define these with any criteria you please.

more information can be found at the MSDN documentation site

the reason you're getting errors when you don't write a CompareTo, is because if you didn't have one, your class wouldn't actually implement IComparable

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top