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

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

    The class that does this already exists! Take a look at the Microsoft C# Samples for Visual Studio: http://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=csharpsamples&ReleaseId=8

    Specifically, look at the ObjectDumper sample as it goes n-levels deep. For example:

    ClassB myBObject = new ClassB();
    ...
    ObjectDumper.Write(myBObject, Int32.MaxValue); 
    //Default 3rd argument value is Console.Out, but you can use 
    //any TextWriter as the optional third argument
    

    It has already taken into account whether an object in the graph has been visited, Value types vs. object types vs. enumerable types, etc.

提交回复
热议问题