C#反射获取字段或属性按名称字段、反射、属性、名称

2023-09-04 11:07:15 作者:别摆脸

有没有办法提供一个名称,一个函数,然后返回这个名字的特定对象在任一领域或财产的价值?我试图解决它与空COALESCE运营商,但显然并不喜欢不同类型的(这也是有点怪我,因为空为空)。我可以分开它出来到是否为空,但必须有一个更好的方式来做到这一点。这里是我的功能,以及两行比较对象不进行编译,但我会离开他们在那里表现出什么,我试图做的。

Is there a way to supply a name to a function that then returns the value of either the field or property on a given object with that name? I tried to work around it with the null-coalesce operator, but apparently that doesn't like different types (which is also a bit weird to me because null is null). I could separate it it out into if nulls, but there has to be a better way to do this. Here is my function, and the two lines with Comparison objects don't compile, but I will leave them in there to show what I am trying to do.

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可以用来,但为了学习,我做我的方式。

I have heard of something called dynamic linq that could be used, but for the sake of learning, I am doing it my way.

推荐答案

更​​改此行:

MemberInfo info = type.GetField(memberName) ?? type.GetProperty(memberName);

这样:

MemberInfo info = type.GetField(memberName) as MemberInfo ??
    type.GetProperty(memberName) as MemberInfo;

因为使用三元运算符一样,如果没有隐式转换为基类。三元要求所有输出的类型是相同的。

because there's no implicit cast to the base class when using the ternary operator like that. The ternary requires that the types of all outputs be the same.