Serialize & print the entire state of an object while debugging
While debugging an ASP.NET application, I want to get a print-out of the entire state of a very large object. I want all the properties and values in that object and the same for every object-property, recursively.
Because the front-end of the application times out after a significant delay, I can't add a watch or use the Immediate window开发者_如何转开发 or hover over the object, since there won't be adequite time to fully examine the object.
Is there a way of getting a complete printout of an object in debug mode, or say, a utility or a C# function that would do this?
You could use reflection to get the list of all properties and fields on the class type, then use that to get the runtime values of each of those properties / values and spit them to the console.
The PropertyInfo
type (here) and FieldInfo
type (here) are what you need to get from the Type
object for your own class instance.
MyObject myObject = ... //setup my object
Type myType = myObject.GetType(); //or Type.GetType(myObject); //I think
PropertyInfo[] properties = myType.GetProperties();
FieldInfo[] fields = myType.GetFields();
properties[0].GetValue(myObject); //returns the value as an Object, so you may need to cast it afterwards.
Reflection really is your best bet here. You can start with your root object, get all of its properties and their values, and if necessary get the properties and values off of those values recursively. It's a really powerful technique, and if you don't know it yet you probably should learn it anyway, and this makes a perfect project to learn with. :)
精彩评论