用Comparison 委托方法进行list双重排序,利用Comparison构造一个方法,此方法接收两个相同类型的参数,返回比较结果(int),下面示例程序,就是利用Comparison委托方法对list进行排序,其中涉及到反射知识。
排序之前:
public int Compare<T>(T info1, T info2)
{
int result;
Type type = typeof(T);
CaseInsensitiveComparer ObjectCompare = new CaseInsensitiveComparer();
result = ObjectCompare.Compare(type.GetProperty("Years").GetValue(info1, null),
type.GetProperty("Years").GetValue(info2, null));
//-------------------如果相等,进行二重排序-----------------------
if (result == 0) result = ObjectCompare.Compare(
type.GetProperty("Qrts").GetValue(info1, null),
type.GetProperty("Qrts").GetValue(info2, null));
return result;
}
调用:
List<DataQrtsORthrInfo> pMyList;
Comparison<MyListInfo> comSort =new Comparison<MyListInfo>(Compare<MyListInfo>);
pMyList.Sort (comSort);
排序之后:
-------------------------------------------------------------------------------------------------------------------
关于利用反射动态的获取对象的属性值
MyListInfo myObj = new MyListInfo ();
我们要动态的获取这个实例的属性Years值,那么得先得到这个实例的类型:
Type t = typeof(MyListInfo);
另一种方法是:
Type t = myObj.GetType();
只要我们得到了对象的类型那么我们就可以利用反射对这个对象“为所欲为”了。
利用反射获取属性值的方法:
int propValue = Convert.ToInt32(t.GetProperty("Years").GetValue(myObj,null));
利用反射给对象里的属性Years赋值了:
t.GetProperty("Years").SetValue(myObj,1,null);
这样我们就为对象里的属性Years赋值了。如果把属性名和要赋的值写道配置文件里的话,我们就可以达到程序运行期间动态的为属性赋值了。
我最近在玩和讯微博,很方便,很实用,你也来和我一起玩吧!
去看看我的微博吧!http://t.hexun.com/3006897/default.html