有没有一种方法可以为函数提供一个名称,然后返回具有该名称的给定对象上的字段或属性的值?我尝试使用null-coalesce运算符解决它,但显然它不喜欢不同的类型(这对我来说也有点奇怪,因为null就是null)。我可以将其分开成if nulls,但肯定有更好的方法来做到这一点。这是我的函数,带有
我听说过一种叫做动态 LINQ 的东西,可以使用它来实现,但为了学习的目的,我会按照我的方式进行操作。
Comparison
对象的两行无法编译,但我会将它们留在那里以显示我想要做的事情。private void SortByMemberName<T>(List<T> list, string memberName, bool ascending)
{
Type type = typeof (T);
MemberInfo info = type.GetField(memberName) ?? type.GetProperty(memberName);
if (info == null)
{
throw new Exception("Member name supplied is neither a field nor property of type " + type.FullName);
}
Comparison<T> asc = (t1, t2) => ((IComparable) info.GetValue(t1)).CompareTo(info.GetValue(t2));
Comparison<T> desc = (t1, t2) => ((IComparable) info.GetValue(t2)).CompareTo(info.GetValue(t1));
list.Sort(ascending ? asc : desc);
}
我听说过一种叫做动态 LINQ 的东西,可以使用它来实现,但为了学习的目的,我会按照我的方式进行操作。
FieldInfo
不是PropertyInfo
。使用as
进行强制类型转换。 - FlyingStreudel