对象转储器类

发布于 2024-08-03 16:55:38 字数 863 浏览 13 评论 0 原文

我正在寻找一个可以以类似于此的格式输出对象及其所有叶值的类:(

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

或更清晰的格式)。这相当于:

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; }
}

PropertyGrid 控件的一种字符串表示形式,无需为每种类型实现大量设计器。

PHP 有一个叫做 var_dump 的东西可以做到这一点。我不想使用手表,因为这是用于打印的。

如果存在的话,有人可以向我指出这样的事情吗?或者,写一篇以获得赏金。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

云裳 2024-08-10 16:55:38

sgmoore 链接中发布的对象转储程序:

//Copyright (C) Microsoft Corporation.  All rights reserved.

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

// See the ReadMe.html for additional information
public class ObjectDumper {

    public static void Write(object element)
    {
        Write(element, 0);
    }

    public static void Write(object element, int depth)
    {
        Write(element, depth, Console.Out);
    }

    public static void Write(object element, int depth, TextWriter log)
    {
        ObjectDumper dumper = new ObjectDumper(depth);
        dumper.writer = log;
        dumper.WriteObject(null, element);
    }

    TextWriter writer;
    int pos;
    int level;
    int depth;

    private ObjectDumper(int depth)
    {
        this.depth = depth;
    }

    private void Write(string s)
    {
        if (s != null) {
            writer.Write(s);
            pos += s.Length;
        }
    }

    private void WriteIndent()
    {
        for (int i = 0; i < level; i++) writer.Write("  ");
    }

    private void WriteLine()
    {
        writer.WriteLine();
        pos = 0;
    }

    private void WriteTab()
    {
        Write("  ");
        while (pos % 8 != 0) Write(" ");
    }

    private void WriteObject(string prefix, object element)
    {
        if (element == null || element is ValueType || element is string) {
            WriteIndent();
            Write(prefix);
            WriteValue(element);
            WriteLine();
        }
        else {
            IEnumerable enumerableElement = element as IEnumerable;
            if (enumerableElement != null) {
                foreach (object item in enumerableElement) {
                    if (item is IEnumerable && !(item is string)) {
                        WriteIndent();
                        Write(prefix);
                        Write("...");
                        WriteLine();
                        if (level < depth) {
                            level++;
                            WriteObject(prefix, item);
                            level--;
                        }
                    }
                    else {
                        WriteObject(prefix, item);
                    }
                }
            }
            else {
                MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
                WriteIndent();
                Write(prefix);
                bool propWritten = false;
                foreach (MemberInfo m in members) {
                    FieldInfo f = m as FieldInfo;
                    PropertyInfo p = m as PropertyInfo;
                    if (f != null || p != null) {
                        if (propWritten) {
                            WriteTab();
                        }
                        else {
                            propWritten = true;
                        }
                        Write(m.Name);
                        Write("=");
                        Type t = f != null ? f.FieldType : p.PropertyType;
                        if (t.IsValueType || t == typeof(string)) {
                            WriteValue(f != null ? f.GetValue(element) : p.GetValue(element, null));
                        }
                        else {
                            if (typeof(IEnumerable).IsAssignableFrom(t)) {
                                Write("...");
                            }
                            else {
                                Write("{ }");
                            }
                        }
                    }
                }
                if (propWritten) WriteLine();
                if (level < depth) {
                    foreach (MemberInfo m in members) {
                        FieldInfo f = m as FieldInfo;
                        PropertyInfo p = m as PropertyInfo;
                        if (f != null || p != null) {
                            Type t = f != null ? f.FieldType : p.PropertyType;
                            if (!(t.IsValueType || t == typeof(string))) {
                                object value = f != null ? f.GetValue(element) : p.GetValue(element, null);
                                if (value != null) {
                                    level++;
                                    WriteObject(m.Name + ": ", value);
                                    level--;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void WriteValue(object o)
    {
        if (o == null) {
            Write("null");
        }
        else if (o is DateTime) {
            Write(((DateTime)o).ToShortDateString());
        }
        else if (o is ValueType || o is string) {
            Write(o.ToString());
        }
        else if (o is IEnumerable) {
            Write("...");
        }
        else {
            Write("{ }");
        }
    }
}

2015 Update

完成此操作的方法

YAML 也很好地满足了此目的,这就是使用 YamlDotNet install-package YamlDotNet

    private static void DumpAsYaml(object o)
    {
        var stringBuilder = new StringBuilder();
        var serializer = new Serializer();
        serializer.Serialize(new IndentedTextWriter(new StringWriter(stringBuilder)), o);
        Console.WriteLine(stringBuilder);
    }

The object dumper posted in sgmoore's link:

//Copyright (C) Microsoft Corporation.  All rights reserved.

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

// See the ReadMe.html for additional information
public class ObjectDumper {

    public static void Write(object element)
    {
        Write(element, 0);
    }

    public static void Write(object element, int depth)
    {
        Write(element, depth, Console.Out);
    }

    public static void Write(object element, int depth, TextWriter log)
    {
        ObjectDumper dumper = new ObjectDumper(depth);
        dumper.writer = log;
        dumper.WriteObject(null, element);
    }

    TextWriter writer;
    int pos;
    int level;
    int depth;

    private ObjectDumper(int depth)
    {
        this.depth = depth;
    }

    private void Write(string s)
    {
        if (s != null) {
            writer.Write(s);
            pos += s.Length;
        }
    }

    private void WriteIndent()
    {
        for (int i = 0; i < level; i++) writer.Write("  ");
    }

    private void WriteLine()
    {
        writer.WriteLine();
        pos = 0;
    }

    private void WriteTab()
    {
        Write("  ");
        while (pos % 8 != 0) Write(" ");
    }

    private void WriteObject(string prefix, object element)
    {
        if (element == null || element is ValueType || element is string) {
            WriteIndent();
            Write(prefix);
            WriteValue(element);
            WriteLine();
        }
        else {
            IEnumerable enumerableElement = element as IEnumerable;
            if (enumerableElement != null) {
                foreach (object item in enumerableElement) {
                    if (item is IEnumerable && !(item is string)) {
                        WriteIndent();
                        Write(prefix);
                        Write("...");
                        WriteLine();
                        if (level < depth) {
                            level++;
                            WriteObject(prefix, item);
                            level--;
                        }
                    }
                    else {
                        WriteObject(prefix, item);
                    }
                }
            }
            else {
                MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
                WriteIndent();
                Write(prefix);
                bool propWritten = false;
                foreach (MemberInfo m in members) {
                    FieldInfo f = m as FieldInfo;
                    PropertyInfo p = m as PropertyInfo;
                    if (f != null || p != null) {
                        if (propWritten) {
                            WriteTab();
                        }
                        else {
                            propWritten = true;
                        }
                        Write(m.Name);
                        Write("=");
                        Type t = f != null ? f.FieldType : p.PropertyType;
                        if (t.IsValueType || t == typeof(string)) {
                            WriteValue(f != null ? f.GetValue(element) : p.GetValue(element, null));
                        }
                        else {
                            if (typeof(IEnumerable).IsAssignableFrom(t)) {
                                Write("...");
                            }
                            else {
                                Write("{ }");
                            }
                        }
                    }
                }
                if (propWritten) WriteLine();
                if (level < depth) {
                    foreach (MemberInfo m in members) {
                        FieldInfo f = m as FieldInfo;
                        PropertyInfo p = m as PropertyInfo;
                        if (f != null || p != null) {
                            Type t = f != null ? f.FieldType : p.PropertyType;
                            if (!(t.IsValueType || t == typeof(string))) {
                                object value = f != null ? f.GetValue(element) : p.GetValue(element, null);
                                if (value != null) {
                                    level++;
                                    WriteObject(m.Name + ": ", value);
                                    level--;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void WriteValue(object o)
    {
        if (o == null) {
            Write("null");
        }
        else if (o is DateTime) {
            Write(((DateTime)o).ToShortDateString());
        }
        else if (o is ValueType || o is string) {
            Write(o.ToString());
        }
        else if (o is IEnumerable) {
            Write("...");
        }
        else {
            Write("{ }");
        }
    }
}

2015 Update

YAML also serves this purpose quite well, this is how it can be done with YamlDotNet

install-package YamlDotNet

    private static void DumpAsYaml(object o)
    {
        var stringBuilder = new StringBuilder();
        var serializer = new Serializer();
        serializer.Serialize(new IndentedTextWriter(new StringWriter(stringBuilder)), o);
        Console.WriteLine(stringBuilder);
    }
栀子花开つ 2024-08-10 16:55:38

您可以使用 JSON 序列化程序,对于任何使用 JSON 的人来说都应该很容易阅读

User theUser = new User();
theUser.Name = "Joe";
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, theUser );
string json = Encoding.Default.GetString(ms.ToArray()); 

You could use the JSON serialiser, which should be easy to read for anyone use to working with JSON

User theUser = new User();
theUser.Name = "Joe";
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, theUser );
string json = Encoding.Default.GetString(ms.ToArray()); 
紧拥背影 2024-08-10 16:55:38

2019 年更新

您可以在 GitHub 上找到 ObjectDumper 项目。您还可以通过 NuGet 包管理器通过 Visual Studio 添加它

Updated 2019

You can find the ObjectDumper project on GitHub. You can also add it via Visual Studio via NuGet package manager.

你的心境我的脸 2024-08-10 16:55:38

如果您使用标记,System.Web.ObjectInfo.PrintASP.NET Web Pages 2)将完成此任务,并针对 HTML 进行了良好的格式化。

例如:

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

在网页中,生成:

ObjectInfo.Print(...)

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(...)

情丝乱 2024-08-10 16:55:38

这是我为此编写的一个 Visual Studio 扩展:

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

实际操作:
正在运行的对象导出器

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

已下线请稍等 2024-08-10 16:55:38

我知道这是一个老问题,但我想我应该放弃一个对我有用的替代方案,花了我大约两分钟的时间。

安装Newtonsoft Json.NET:
http://james.newtonking.com/json

(或 nuget 版本)http://www.nuget.org/packages/newtonsoft.json/

参考程序集:

using Newtonsoft.Json;

转储 JSON 字符串到日志:

txtResult.Text = JsonConvert.SerializeObject(testObj);

I know this is an old question, but thought I'd throw out an alternative that worked for me, took me about two minutes to do.

Install Newtonsoft Json.NET:
http://james.newtonking.com/json

(or nuget version) http://www.nuget.org/packages/newtonsoft.json/

Reference Assembly:

using Newtonsoft.Json;

Dump JSON string to log:

txtResult.Text = JsonConvert.SerializeObject(testObj);
灯下孤影 2024-08-10 16:55:38

只要稍加思考,你就可以很容易地写出它。类似于:

public void Print(object value, int depth)
{
    foreach(var property in value.GetType().GetProperties())
    {
        var subValue = property.GetValue(value);
        if(subValue is IEnumerable)
        {
             PrintArray(property, (IEnumerable)subValue);
        }
        else
        {
             PrintProperty(property, subValue);
        }         
    }
}

您可以编写 PrintArray 和 PrintProperty 方法。

You could write that very easily with a little bit of reflection. Something kind of like:

public void Print(object value, int depth)
{
    foreach(var property in value.GetType().GetProperties())
    {
        var subValue = property.GetValue(value);
        if(subValue is IEnumerable)
        {
             PrintArray(property, (IEnumerable)subValue);
        }
        else
        {
             PrintProperty(property, subValue);
        }         
    }
}

You can write up the PrintArray and PrintProperty methods.

陌伤浅笑 2024-08-10 16:55:38

我有一个 方便的 T.Dump() 扩展方法,它应该非常接近您正在寻找的结果。作为一种扩展方法,它是非侵入性的,并且应该适用于所有 POCO 对象。

用法示例

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

输出示例

{
    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
    }
}

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
    }
}
昵称有卵用 2024-08-10 16:55:38

如果您不想复制和粘贴 Chris S 的代码,Visual Studio 2008 示例附带了一个 ObjectDumper。

驱动器:\Program Files\Microsoft Visual Studio 9.0\Samples\1033\LinqSamples\ObjectDumper

If you don't feel like copying and pasting Chris S's code, the Visual Studio 2008 samples come with an ObjectDumper.

Drive:\Program Files\Microsoft Visual Studio 9.0\Samples\1033\LinqSamples\ObjectDumper

决绝 2024-08-10 16:55:38

这是一个替代方案:(

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);
}

只是触及第 1 级,没有深度,但说了很多)

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)

九厘米的零° 2024-08-10 16:55:38

对于大多数类,您可以使用 DataContractSerializer

For most classes, you could use the DataContractSerializer

忘你却要生生世世 2024-08-10 16:55:38

我刚刚在 Blazor 项目中遇到了类似的要求,并提出了以下非常简单的组件来将对象(及其子对象)的数据输出到屏幕:

ObjectDumper.razor:

@using Microsoft.AspNetCore.Components
@using Newtonsoft.Json

  <div>
    <button onclick="@DumpVMToConsole">@ButtonText</button>
    <pre id="json">@_objectAsJson</pre>
  </div>


@functions {

  // This component allows the easy visualisation of the values currently held in 
  // an object and its child objects.  Add this component to a page and pass in a 
  // param for the object to monitor, then press the button to see the object's data
  // as nicely formatted JSON
  // Use like this:  <ObjectDumper ObjectToDump="@_billOfLadingVM" />

  [Parameter]
  private object ObjectToDump { get; set; }

  [Parameter]
  private string ButtonText { get; set; } = "Show object's data";

  string _buttonText;

  string _objectAsJson = "";

  public void DumpVMToConsole()
  {
    _objectAsJson = GetObjectAsFormattedJson(ObjectToDump);
    Console.WriteLine(_objectAsJson);
  }

  public string GetObjectAsFormattedJson(object obj)
  {
    return JsonConvert.SerializeObject(
      value: obj, 
      formatting: Formatting.Indented, 
      settings: new JsonSerializerSettings
      {
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
      });
  }

}

然后将其粘贴到 Blazor 页面上的某个位置如下所示:

<ObjectDumper ObjectToDump="@YourObjectToVisualise" />

然后呈现一个按钮,您可以按下该按钮来查看绑定对象的当前值:

在此处输入图像描述

我已将其粘贴在 GitHub 存储库中:tomRedox/BlazorObjectDumper

I just came across a similar requirement in a Blazor project, and came up with the following very simple component to output an object's (and it's child objects') data to the screen:

ObjectDumper.razor:

@using Microsoft.AspNetCore.Components
@using Newtonsoft.Json

  <div>
    <button onclick="@DumpVMToConsole">@ButtonText</button>
    <pre id="json">@_objectAsJson</pre>
  </div>


@functions {

  // This component allows the easy visualisation of the values currently held in 
  // an object and its child objects.  Add this component to a page and pass in a 
  // param for the object to monitor, then press the button to see the object's data
  // as nicely formatted JSON
  // Use like this:  <ObjectDumper ObjectToDump="@_billOfLadingVM" />

  [Parameter]
  private object ObjectToDump { get; set; }

  [Parameter]
  private string ButtonText { get; set; } = "Show object's data";

  string _buttonText;

  string _objectAsJson = "";

  public void DumpVMToConsole()
  {
    _objectAsJson = GetObjectAsFormattedJson(ObjectToDump);
    Console.WriteLine(_objectAsJson);
  }

  public string GetObjectAsFormattedJson(object obj)
  {
    return JsonConvert.SerializeObject(
      value: obj, 
      formatting: Formatting.Indented, 
      settings: new JsonSerializerSettings
      {
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
      });
  }

}

You then stick that somewhere on a Blazor page as follows:

<ObjectDumper ObjectToDump="@YourObjectToVisualise" />

Which then renders a button you can press to see the current values of the bound object:

enter image description here

I've stuck that in a GitHub repo: tomRedox/BlazorObjectDumper

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文