摘要:(2010-08-02) C#.NET 實作 IComparable 介面
自定類別
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mod01
{
public class Employee:System.IComparable<Employee>
{
//Data Field
private Int32 _id;
public Int32 Id
{
get { return _id; }
set { _id = value; }
}
private Decimal _salary;
public Decimal Salary
{
get { return _salary; }
set { _salary = value; }
}
private String _name;
public String Name
{
get { return _name; }
set { _name = value; }
}
public Employee() { }
//解構子
~Employee()
{
//類別成員
AppUtil.writeMsg(@"c:\mylog.txt","Employee解構了!!"+DateTime.Now.ToString());
}
#region IComparable<Employee> 成員
public int CompareTo(Employee other)
{
Int32 r = 0; // 相等
if (this.Id > other.Id)
{
r = 1;
}
if (this.Id < other.Id)
{
r = -1;
}
return r;
}
#endregion
}
}主程式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mod01
{
class TestSortEmployee
{
public static void Main()
{
// 定義陣列
Employee[] emps = {
new Employee(){ Id=10, Name="eric", Salary=50000},
new Employee(){ Id=1, Name="sam", Salary=20000},
new Employee(){ Id=3, Name="bill", Salary=100000},
new Employee(){ Id=2, Name="linda", Salary=30000},
};
//重新排序
System.Array.Sort(emps);
foreach (Employee e in emps)
{
System.Console.WriteLine(e.Id.ToString());
}
}
}
}輸出
1
2
3
10