简体   繁体   中英

How to get properties from FieldInfo in C#?

I have this method and want to get all properties from the 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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