我正在寻找一个可以输出对象及其所有叶值的类,其格式与此类似:
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的东西。我不想使用手表,因为这是用于打印出来的。
如果它存在,有人能指出这样的事吗?或者,写一个赏金。
答案 0 :(得分:50)
在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("{ }");
}
}
}
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);
}
答案 1 :(得分:31)
你可以使用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());
答案 2 :(得分:14)
2019年更新
您可以在GitHub上找到ObjectDumper project。您还可以通过Visual Studio通过NuGet包管理器add it。
答案 3 :(得分:13)
如果您正在使用标记,System.Web.ObjectInfo.Print
( ASP.NET网页2 )将完成此操作,格式化为HTML格式。
例如:
@ObjectInfo.Print(new {
Foo = "Hello",
Bar = "World",
Qux = new {
Number = 42,
},
})
在网页中,生成:
答案 4 :(得分:12)
这是我为此写的视觉工作室扩展:
https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f
在行动中:
答案 5 :(得分:7)
你可以通过一点反思很容易地写出来。有点像:
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方法。
答案 6 :(得分:7)
我有一个handy T.Dump() Extension method应该非常接近您正在寻找的结果。作为一种扩展方法,它的非侵入性应该适用于所有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
}
}
答案 7 :(得分:7)
我知道这是一个老问题,但我想我会抛出一个对我有用的替代方案,花了我两分钟左右的时间。
安装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);
答案 8 :(得分:2)
如果您不想复制和粘贴Chris S的代码,Visual Studio 2008示例会附带一个ObjectDumper。
驱动器:\ Program Files \ Microsoft Visual Studio 9.0 \ Samples \ 1033 \ LinqSamples \ ObjectDumper
答案 9 :(得分:2)
这是另一种选择:
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级,没有深度,但说了很多)
答案 10 :(得分:1)
对于大多数课程,您可以使用DataContractSerializer
答案 11 :(得分:0)
我刚刚在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