When to use IComparable Vs. IComparer

前端 未结 8 1291
[愿得一人]
[愿得一人] 2020-11-29 16:07

I\'m trying to figure out which of these interfaces I need to implement. They both essentially do the same thing. When would I use one over the other?

8条回答
  •  野性不改
    2020-11-29 16:50

    It depends on the entity. For example following for a class like "Student", it will make sense to have IComparable based on Name.

    class Student : IComparable 
    {
        public string Name { get; set; }
        public int MathScore { get; set; }
        public int EnglishScore { get; set; }
    
        public int TotalScore 
        {
            get
            {
                return this.MathScore + this.EnglishScore; 
            }
        }
    
        public int CompareTo(object obj)
        {
            return CompareTo(obj as Student);  
        }
    
        public int CompareTo(Student other)
        {
            if (other == null)
            {
                return 1;
            }
            return this.Name.CompareTo(other.Name);  
        }
    }
    

    But if a teacher 'A' wants to compare students based on MathScore, and teacher 'B' wants to compare students based on EnglishScore. It will be good idea to implement IComparer separately. (More like a strategy pattern)

    class CompareByMathScore : IComparer
    {
        public int Compare(Student x, Student y)
        {
            if (x.MathScore > y.MathScore)
              return 1;
            if (x.MathScore < y.MathScore)
              return -1;
            else
              return 0;
        }
    }
    

提交回复
热议问题