在工作中經常會遇到對象數組根據某個屬性進行排序的問題
以汽車為例
private int weight;
public int Weight
{
get { return weight; }
set { weight = value; }
}
private string type;
public string Type
{
get { return type; }
set { type = value; }
}
}
Car[] cars
我們將類Car實現接口IComparable使其能夠使用Array
代碼如下
public class Car:IComparable<Car>
{
private int weight;
public int Weight
{
get { return weight; }
set { weight = value; }
}
private string type;
public string Type
{
get { return type; }
set { type = value; }
}
IComparable 成員#region IComparable<Employee> 成員
public int CompareTo(Car other)
{
if (this
return
if (this
return
return
}
#endregion
}實現該方法以後我們就可以直接使用如下代碼來對cars進行排序了
Car[] arr = new Car[] {car
Array
不用擔心我們只要使用一個最簡單的Adapter模式就能解決這個問題
下面我們來創建這個適配器
public class ComparaCarAdapter : IComparer<Car>
{
IComparer 成員#region IComparer<Car> 成員
public int Compare(Car x
{
return x
}
#endregion
}然後如此調用
Array
public class ComparaCarAdapter : IComparer<Car>
{
string _progName =
public ComparaCarAdapter(string progName)
{
_progName = progName;
}
IComparer 成員#region IComparer<Employee> 成員
public int Compare(Car x
{
Type t = typeof(Car);
PropertyInfo pi = t
object xvalue = pi
object yvalue = pi
if (xvalue is string)
{
return ((string)xvalue)
}
else
{
if (xvalue is int)
return ((int)xvalue)
}
throw new NotSupportedException();
}
#endregion
}
調用 Array
From:http://tw.wingwit.com/Article/program/ASP/201311/21665.html