首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

.NET 程式設計介面剖析 (1):比較與排序介面

     編輯:關於C語言

介面的本質

介面是對類別能力的標準化認證。實作介面 = 擁有該能力。如 IComparable 代表「可比較大小」,IEnumerable 代表「可列舉」。

IComparable & IComparable<T>

public interface IComparable
{
    int CompareTo(object obj);
}
  • 回傳負數:目前實例較小;0:相等;正數:較大。
  • 實作後,List<T>.Sort()、Array.Sort() 即可自動排序。

完整範例:Student 類別依姓名排序

public enum SubjectEnum { Total, Chinese, English, Math }

public class Scores
{
    int[] _score = new int[4];
    public int this[SubjectEnum s] { get { return _score[(int)s]; } set { _score[(int)s] = value; } }
    public override string ToString() { /* 略 */ }
}

public class Student : IComparable
{
    string _name;
    public string Name { get { return _name; } set { _name = value; } }
    public Scores Scores { get; set; }

    public Student(string name, int chinese, int english, int math)
    {
        _name = name;
        Scores[SubjectEnum.Chinese] = chinese;
        Scores[SubjectEnum.English] = english;
        Scores[SubjectEnum.Math] = math;
        Scores[SubjectEnum.Total] = chinese + english + math;
    }

    public int CompareTo(object obj)
    {
        if (!(obj is Student)) throw new ArgumentException("Not a Student");
        return Name.CompareTo(((Student)obj).Name);
    }
}

後續文章將介紹 IComparer、IEnumerable/IEnumerator、序列化介面等。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved