更新时间:2023-11-05 11:21:40
对于其他人发布的内容,我会提供这个替代方案.
I would offer this alternative to what everyone else has posted.
System.Reflection.PropertyInfo prop = typeof(YourType).GetProperty("PropertyName");
query = query.OrderBy(x => prop.GetValue(x, null));
这避免了重复调用反射 API 来获取属性.现在唯一的重复调用就是获取值.
This avoids repeated calls to the reflection API for obtaining the property. Now the only repeated call is obtaining the value.
不过
我提倡使用 PropertyDescriptor
代替,因为这将允许将自定义 TypeDescriptor
分配给您的类型,从而可以进行轻量级操作来检索属性和价值观.在没有自定义描述符的情况下,它无论如何都会回退到反射.
I would advocate using a PropertyDescriptor
instead, as this will allow for custom TypeDescriptor
s to be assigned to your type, making it possible to have lightweight operations for retrieving properties and values. In the absence of a custom descriptor it will fall back to reflection anyhow.
PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(YourType)).Find("PropertyName");
query = query.OrderBy(x => prop.GetValue(x));
至于加快速度,请查看 Marc Gravel 的 HyperDescriptor
CodeProject 上的项目.我已经成功地使用了它;它是对业务对象进行高性能数据绑定和动态属性操作的救星.
As for speeding it up, check out Marc Gravel's HyperDescriptor
project on CodeProject. I've used this with great success; it's a life saver for high-performance data binding and dynamic property operations on business objects.