介面是對類別能力的標準化認證。實作介面 = 擁有該能力。如 IComparable 代表「可比較大小」,IEnumerable 代表「可列舉」。
public interface IComparable
{
int CompareTo(object obj);
}
List<T>.Sort()、Array.Sort() 即可自動排序。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、序列化介面等。