object dumper class

2019-01-04 07:01发布

I'm looking for a class that can output an object and all its leaf values in a format similar to this:

User
  - Name: Gordon
  - Age : 60
  - WorkAddress
     - Street: 10 Downing Street
     - Town: London
     - Country: UK
  - HomeAddresses[0]
    ...
  - HomeAddresses[1]
    ...

(Or a clearer format). This would be equivalent to:

public class User
{
    public string Name { get;set; }
    public int Age { get;set; }
    public Address WorkAddress { get;set; }
    public List<Address> HomeAddresses { get;set; }
}

public class Address
{
    public string Street { get;set; }
    public string Town { get;set; }
    public string Country { get;set; }
}

A kind of string representation of the PropertyGrid control, minus having to implement a large set of designers for each type.

PHP has something that does this called var_dump. I don't want to use a watch, as this is for printing out.

Could anyone point me to something like this if it exists? Or, write one for a bounty.

11条回答
男人必须洒脱
2楼-- · 2019-01-04 07:58

You can find the ObjectDumper project on CodePlex. You can also add it via Visual Studio 2010 Nuget package manager.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-04 07:58

Here is an alternative:

using System.Reflection;
public void Print(object value)
{
    PropertyInfo[] myPropertyInfo;
    string temp="Properties of "+value+" are:\n";
    myPropertyInfo = value.GetType().GetProperties();
    for (int i = 0; i < myPropertyInfo.Length; i++)
    {
        temp+=myPropertyInfo[i].ToString().PadRight(50)+" = "+myPropertyInfo[i].GetValue(value, null)+"\n";
    }
    MessageBox.Show(temp);
}

(just touching level 1, no depth, but says a lot)

查看更多
甜甜的少女心
4楼-- · 2019-01-04 07:59

Here's a visual studio extension I wrote to do this:

https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f

in action: object exporter in action

查看更多
放我归山
5楼-- · 2019-01-04 08:00

If you're working with markup, System.Web.ObjectInfo.Print (ASP.NET Web Pages 2) will accomplish this, nicely formatted for HTML.

For example:

@ObjectInfo.Print(new {
    Foo = "Hello",
    Bar = "World",
    Qux = new {
        Number = 42,
    },
})

In a webpage, produces:

ObjectInfo.Print(...)

查看更多
forever°为你锁心
6楼-- · 2019-01-04 08:00

I have a handy T.Dump() Extension method that should be pretty close to the results you're looking for. As its an extension method, its non-invasive and should work on all POCO objects.

Example Usage

var model = new TestModel();
Console.WriteLine(model.Dump());

Example Output

{
    Int: 1,
    String: One,
    DateTime: 2010-04-11,
    Guid: c050437f6fcd46be9b2d0806a0860b3e,
    EmptyIntList: [],
    IntList:
    [
        1,
        2,
        3
    ],
    StringList:
    [
        one,
        two,
        three
    ],
    StringIntMap:
    {
        a: 1,
        b: 2,
        c: 3
    }
}
查看更多
登录 后发表回答