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

前端 未结 5 1787
轻奢々
轻奢々 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:20

    Here's a naive implementation:

        private static void ListFields(Type type)
        {
            Console.WriteLine(type.Name);
            foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                Console.WriteLine(string.Format("{0} of type {1}", field.Name, field.FieldType.Name));
                if (field.FieldType.IsClass)
                {
                    ListFields(field.FieldType);
                }
    
            }
        }
    

    Some things to note:

    • Prevent a stack overflow. That is if a -> b and b-> a then this will blow up. You can resolve this by only resolving down to a certain level
    • A string is a reference type but lots of people expect it to be more like a value type. So you might not want to call ListFields if the type is string.

提交回复
热议问题