开发者

How to get properties from FieldInfo in C#?

开发者 https://www.devze.com 2022-12-13 06:20 出处:网络
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)

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(fi开发者_开发知识库eld);
     }

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

精彩评论

暂无评论...
验证码 换一张
取 消