




















但是这样如果属性很多,会产生很多的类,怎么办呢。那么利用反射吧。将ComparaCarAdapter改造为:
public class ComparaCarAdapter : IComparer<Car>
{
string _progName = "";
public ComparaCarAdapter(string progName)
{
_progName = progName;
}
#region IComparer<Employee> 成员

public int Compare(Car x, Car y)
{
Type t = typeof(Car);
PropertyInfo pi = t.GetProperty(_progName);
object xvalue = pi.GetValue(x, null);
object yvalue = pi.GetValue(y, null);
if (xvalue is string)
{
return ((string)xvalue).CompareTo((string)yvalue);
}
else
{
if (xvalue is int)
return ((int)xvalue).CompareTo((int)yvalue);
}
throw new NotSupportedException();
}

#endregion
}
调用
Array.Sort<Car>(arr, new ComparaCarAdapter("Weight"));
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。