2014-04-04 32 views
1

这是我第一篇文章。我在尝试做类似的课程时遇到问题,我希望你能帮助我。在制作可比较课程时遇到问题

错误:

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

实现你已经实现了两个IComparableIcomparable<T>。 所以你必须实现两个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

错误消息确切说你错过了什么。

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