سؤال

This is my first post here. I'm having problems with trying to make an comparable class, and i was hoping you could help me out.

The error:

Error 1 'OutputMasterLibrary.Student' does not implement interface member 'System.Collections.Generic.IComparer.Compare(OutputMasterLibrary.Student, OutputMasterLibrary.Student)''

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OutputMasterLibrary 
{
    public class Student : IComparable, IComparable<Student>
    {
        string name { get; set; }
        int age { get; set; }
        int studentNumber { get; set; }


        public Student(string myName, int myAge, int myNumber)
        {
            name = myName;
            age = myAge;
            studentNumber = myNumber;
        }


        public override bool Equals(object obj)
        {
            Student other = obj as Student;
            if (other == null)
            {
                return false;
            }
            return (this.name == other.name) && (this.studentNumber == other.studentNumber) && (this.age == other.age);
        }


        public override int GetHashCode()
        {
            return name.GetHashCode() + studentNumber.GetHashCode() + age.GetHashCode();
        }
    }
}
هل كانت مفيدة؟

المحلول 2

You have implemented both IComparable and Icomparable<T>. So you have to implement both CompareTo methods.

    public int CompareTo(object obj) // implement method from IComaparable<T> interface
    {
        return CompareStudent(this, (Student)obj);
    }

    public int CompareTo(Student obj) // implement method from IComaparable interface
    {
        if (obj != null && !(obj is Student))
            throw new ArgumentException("Object must be of type Student.");
        return CompareStudent(this, obj);
    }

    public int CompareStudent(Student st1, Student st2)
    {
        // You can change it as you want
        // I am comparing their ages 
        return st1.age.CompareTo(st2.age);
    }

نصائح أخرى

The error message exactly says what you are missing.

Implement in your Student class

public int Compare(Student student1, Student student2)
public override bool Equals(Student x, Student y)
    {
        if (x == null || y == null)
        {
            return false;
        }
        if (x.Equals(y)) return true;
        return (x.name == y.name) && (x.studentNumber == y.studentNumber) && (y.age == y.age);
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top