曾有写过这么一种程序,将List<Xobject>绑定到GridView中,而这个GridView又有很多列要实现排序功能,而且还有趋势不断增加。难道要根据不同的列写不同的排序方法吗?难道每增加一列就要再多加一个方法?习惯在开发中用偷懒来提高生产效率的我用了反射来应对这种麻烦的需求 。
对List自动排序方法如下:

/**//// <summary>以反射實現List<Xobject>迭代排序</summary>
/// <remarks>此方法作为参数传给List的Sort方法</remarks>
protected int SortXobjectList(Xobject mSource, Xobject mTarget)
...{
Type type = mSource.GetType(); //获得待比较对象的类型
//this.SortField便是要用来排序的属性名,string类型。执行此句后将被实例化为属性对象
PropertyInfo property = type.GetProperty(this.SortField);
object sourceValue = property.GetValue(mSource, null); //获得第一个待比较对象的该属性的值
object targetValue = property.GetValue(mTarget, null); //获得第二个待比较对象的该属性的值
//实例化数据比较的方法。第一个参数是方法名,第二个是该方法的参数类型
MethodInfo method = sourceValue.GetType().GetMethod("CompareTo", new Type[] ...{ targetValue.GetType() });
//终于准备完毕了。此句等价于 mSource.某属性.CompareTo(mTarget.某属性)
return (int)method.Invoke(sourceValue, new object[] ...{ targetValue });
}GridView的排序事件代码如下:
protected void gvXobjectInfo_Sorting(object sender, GridViewSortEventArgs e)
...{
this.SortField = e.SortExpression; //获取并设置排序属性
List<Xobject> listXobject = GetXobjectData(); //获取数据,与本文无关,代码省略
listXobject .Sort(SortXobject); //调用上面的排序方法进行排序
BindData(listXobject ); //绑定数据
}现在我的程序中就只有SortXobjectList这一个排序的方法了,它会根据用户在GridView上点击的标头按其对应的属性排序。当然,GridView中需要排序的列要把其SortExpression属性设置为对应的属性先。
反射实现List自动排序
介绍了一种使用反射机制实现的通用List排序方法,该方法能够根据用户在GridView中选择的不同列进行自动排序,大大简化了排序功能的实现过程。
8804

被折叠的 条评论
为什么被折叠?



