但是这样如果属性很多,会产生很多的类,怎么办呢。那么利用反射吧。将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
}
{
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"));