[英]C# Reflection get Field or Property by Name
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).
我试图用 null-coalesce 运算符解决它,但显然这不喜欢不同的类型(这对我来说也有点奇怪,因为 null 是 null)。 I could separate it it out into if nulls, but there has to be a better way to do this.
我可以将它分成 if nulls,但必须有更好的方法来做到这一点。 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.这是我的函数,带有
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);
}
I have heard of something called dynamic LINQ that could be used, but for the sake of learning, I am doing it my way.我听说过可以使用称为动态 LINQ 的东西,但为了学习,我正在按照自己的方式进行。
Change this line:更改此行:
MemberInfo info = type.GetField(memberName) ?? type.GetProperty(memberName);
to this:对此:
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.
三元要求所有输出的类型相同。
As of C# 9.0 , this will finally be possible:从C# 9.0 开始,这将最终成为可能:
Target typed ??
目标类型 ?? and ?:
和 ?:
Sometimes conditional ??
有时有条件?? and ?: expressions don't have an obvious shared type between the branches.
和 ?: 表达式在分支之间没有明显的共享类型。 Such cases fail today, but C# 9.0 will allow them if there's a target type that both branches convert to:
这种情况今天会失败,但如果存在两个分支都转换为的目标类型,C# 9.0 将允许它们:
Person person = student ?? customer; // Shared base type int? result = b ? 0 : null; // nullable value type
That means the code block in the question will also compile without errors;这意味着问题中的代码块也将编译而不会出错; it will 'see' that
FieldInfo
and PropertyInfo
have a shared base type, MemberInfo
.它将“看到”
FieldInfo
和PropertyInfo
具有共享基类型MemberInfo
。
MemberInfo info = type.GetField(memberName) ?? type.GetProperty(memberName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.