简体   繁体   English

如何从C#中的FieldInfo获取属性?

[英]How to get properties from FieldInfo in C#?

I have this method and want to get all properties from the FieldInfos? 我有此方法,想从FieldInfos获取所有属性吗? How to get it? 如何获得?

  private static void FindFields(ICollection<FieldInfo> fields, Type t)
  {
     var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;

     foreach (var field in t.GetFields(flags))
     {
        fields.Add(field);
     }

     var baseType = t.BaseType;
     if (baseType != null)
     {
        FindFields(fields, baseType);
     }
  }

     var fields = new Collection<FieldInfo>();
     FindFields(fields, this.GetType());

Thanks. 谢谢。

Best regards. 最好的祝福。

To get the value of a field for a specific object use GetValue and pass the object for which you want to get the value. 若要获取特定对象的字段值,请使用GetValue并传递要为其获取值的对象。

var fields = new Collection<FieldInfo>();
FindFields(fields, this.GetType()); 

foreach (var field in fields)
{
    Console.WriteLine( "{0} = {1}", field.Name , field.GetValue(this));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM