如何获取MemberInfo
对象的值? .Name
返回变量的名称,但我需要该值。
我认为您可以使用FieldInfo
执行此操作,但我没有代码段,如果您知道如何执行此操作,您是否可以提供代码段?
谢谢!
答案 0 :(得分:32)
以下是使用FieldInfo.GetValue:
的字段示例using System;
using System.Reflection;
public class Test
{
// public just for the sake of a short example.
public int x;
static void Main()
{
FieldInfo field = typeof(Test).GetField("x");
Test t = new Test();
t.x = 10;
Console.WriteLine(field.GetValue(t));
}
}
类似的代码适用于使用PropertyInfo.GetValue()的属性 - 尽管您还需要将任何参数的值传递给属性。 (对于“普通”C#属性,没有任何内容,但就框架而言,C#索引器也算作属性。)对于方法,如果要调用,则需要调用Invoke方法并使用返回值。
答案 1 :(得分:21)
虽然我普遍同意Marc关于不反映字段的观点,但有时候需要它。如果你想反映一个成员并且你不关心它是一个字段还是一个属性,你可以使用这个扩展方法来获取值(如果你想要类型而不是值,请参阅nawful'回答this question):
public static object GetValue(this MemberInfo memberInfo, object forObject)
{
switch (memberInfo.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)memberInfo).GetValue(forObject);
case MemberTypes.Property:
return ((PropertyInfo)memberInfo).GetValue(forObject);
default:
throw new NotImplementedException();
}
}
答案 2 :(得分:11)
Jon的答案是理想的 - 只有一个观察:作为一般设计的一部分,我会:
这两者的结果是一般你只需要反映公共财产(除非你知道他们做了什么,否则不应该调用方法;属性获取者预期是幂等的[延迟加载])。因此对于PropertyInfo
,这只是prop.GetValue(obj, null);
。
实际上,我是System.ComponentModel
的忠实粉丝,所以我很想使用:
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
{
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
}
或特定财产:
PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)["SomeProperty"];
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
System.ComponentModel
的一个优点是它可以与抽象数据模型一起使用,例如DataView
如何将列公开为虚拟属性;还有其他技巧(如performance tricks)。