2014-04-04 4 views
1

이것은 내 첫 번째 게시물입니다. 필자는 필적할만한 수업을 만드는 데 어려움을 겪고 있으며, 나를 도울 수 있기를 바랬다.Comparable 클래스를 만드는 데 문제가 있음

오류 :

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

내 코드 :

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(); 
     } 
    } 
} 
+0

감사합니다. 그것은 효과가있다! – user236580

+0

IComparer 인터페이스를 지정하지 않았기 때문에 게시 한 코드와 관련된 오류 메시지가 아닌 것 같습니다. Visual Studio를 사용하는 경우 Resharper를 사용하는 것이 좋습니다. 이 도구는 누락 된 인터페이스 메소드를 쉽게 구현하는 데 도움이됩니다. – BlueM

답변

1

에서 구현합니다. 따라서 CompareTo 두 가지 방법을 모두 구현해야합니다.

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

오류 메시지가 정확히이없는 것을 말한다.

당신은 IComparableIcomparable<T> 모두를 구현하여 Student 클래스

public int Compare(Student student1, Student student2) 
1
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); 
    } 
관련 문제