如何在C#中实现类似PHP var_dump的对象数据输出?
C# 实现类似 PHP var_dump 的对象输出效果
PHP的var_dump可以直观输出变量的类型、结构和值,在C#里可以通过以下几种方式实现类似效果:
1. 内置System.Text.Json序列化(无需额外依赖)
利用.NET Core/.NET 5+内置的JSON序列化器,将对象序列化为格式化的JSON,清晰展示属性名、值和类型信息:
using System; using System.Text.Json; class Program { static void Main() { var foo = new Foo { Prop1 = "ABC", Prop2 = 2024 }; // 开启缩进格式化,输出更易读 var options = new JsonSerializerOptions { WriteIndented = true }; string jsonOutput = JsonSerializer.Serialize(foo, options); Console.WriteLine(jsonOutput); } } class Foo { public string Prop1 { get; set; } public int Prop2 { get; set; } }
输出示例:
{ "Prop1": "ABC", "Prop2": 2024 }
2. 反射自定义实现类var_dump格式
如果想要更贴近PHPvar_dump的输出样式,可以通过反射遍历对象属性,手动构造输出内容:
using System; using System.Reflection; class Program { static void Main() { var foo = new Foo { Prop1 = "ABC", Prop2 = 2024 }; VarDump(foo); } static void VarDump(object obj) { if (obj == null) { Console.WriteLine("null"); return; } Type objType = obj.GetType(); Console.WriteLine($"object({objType.Name}) {{"); // 获取对象的所有公共实例属性 PropertyInfo[] properties = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { object propValue = prop.GetValue(obj); string valueType = propValue?.GetType().Name ?? "null"; string valueString = propValue?.ToString() ?? "null"; Console.WriteLine($" [{prop.Name}]=>"); // 对字符串额外显示长度 if (propValue is string strValue) { Console.WriteLine($" string({strValue.Length}) \"{strValue}\""); } else { Console.WriteLine($" {valueType} {valueString}"); } } Console.WriteLine("}"); } } class Foo { public string Prop1 { get; set; } public int Prop2 { get; set; } }
输出示例:
object(Foo) { [Prop1]=> string(3) "ABC" [Prop2]=> Int32 2024 }
3. 第三方库(如Json.NET/Newtonsoft.Json)
如果需要更灵活的序列化配置(比如支持私有属性、循环引用处理等),可以使用Json.NET库:
using Newtonsoft.Json; using System; class Program { static void Main() { var foo = new Foo { Prop1 = "ABC", Prop2 = 2024 }; // 格式化输出JSON string jsonOutput = JsonConvert.SerializeObject(foo, Formatting.Indented); Console.WriteLine(jsonOutput); } } class Foo { public string Prop1 { get; set; } public int Prop2 { get; set; } }
输出示例和内置JSON序列化类似,但支持更多高级特性,需要通过NuGet安装Newtonsoft.Json包。
内容的提问来源于stack exchange,提问作者user24843565
相关产品推荐
相关产品推荐

