我如何获得MemberInfo的值?

如何获取MemberInfo对象的值? .Name返回变量的名称,但我需要该值。

我认为你可以用FieldInfo做到这一点,但我没有一个片段,如果你知道如何做到这一点你能提供一个片段吗?

谢谢!

以下是使用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(); tx = 10; Console.WriteLine(field.GetValue(t)); } } 

类似的代码适用于使用PropertyInfo.GetValue()的属性 – 尽管您还需要将任何参数的值传递给属性。 (对于“普通”C#属性,没有任何内容,但就框架而言,C#索引器也算作属性。)对于方法,如果要调用方法并使用方法,则需要调用Invoke返回值。

虽然我普遍同意Marc关于不reflection场的观点,但有时候需要它。 如果你想反映一个成员并且你不关心它是一个字段还是一个属性,你可以使用这个扩展方法来获取值(如果你想要类型而不是值,请参阅nawful对这个问题的回答) :

  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(); } } 

乔恩的答案是理想的 – 只有一个观察:作为一般设计的一部分,我会:

  1. 一般避免反对非公开成员
  2. 避免拥有公共领域(几乎总是)

这两者的结果是, 通常你只需要反映公共属性(你不应该调用方法,除非你知道他们做了什么;属性getter 预计是幂等的[延迟加载])。 所以对于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如何将列作为虚拟属性公开; 还有其他技巧(比如表演技巧 )。