.NET, C#, Reflection: list the fields of a field that, itself, has fields

前端 未结 5 1790
轻奢々
轻奢々 2020-12-11 08:53

In .NET & C#, suppose ClassB has a field that is of type ClassA. One can easily use method GetFields to list ClassB\'

5条回答
  •  暖寄归人
    2020-12-11 09:08

    Try the following. It lets you control how deep you descend into the type hierarchy and should only descend into non-primitive types.

    public static class FieldExtensions
    {
      public static IEnumerable GetFields( this Type type, int depth )
      {
        if( depth == 0 )
          return Enumerable.Empty();
    
        FieldInfo[] fields = type.GetFields();
        return fields.Union(fields.Where( fi => !fi.IsPrimitive )
                                  .SelectMany( f => f.FieldType.GetFields( depth -1 ) );
      }
    }
    

提交回复
热议问题