【发布时间】:2019-07-18 18:47:46
【问题描述】:
如何将字典转换为定义该字典的 C# 代码? (类似于python中的repr()。)
例子:
var dict = new Dictionary<int, string> {
{ 4, "a" },
{ 5, "b" }
};
Console.WriteLine(dict.ToCsharpString());
输出:
Dictionary<int, string> {
{ 4, "a" },
{ 5, "b" }
}
我对包含原始类型的字典最感兴趣。
类似问题:Most efficient Dictionary.ToString() with formatting?(关注效率)、Is there anyway to handy convert a dictionary to String? (想要不同的输出格式)。
【问题讨论】:
-
为什么不使用answer 中描述的 JSON 序列化器/反序列化器? JSON 在 .NET/C# 中非常容易处理。
-
Dictionary可能有某种形式的自定义比较器(例如不区分大小写)? -
@Odrai:我认为 JSON 序列化程序不会输出到 C#?我将其用于两个目的:快速调试日志(其中 C# 是一种熟悉的数据形式)和生成稍后插入代码中的数据。
-
How can I convert a Dictionary into the C# code that would define that dictionary?如果您尝试生成创建字典的代码,并且原始代码使用了自定义比较器,您是否希望生成的代码也包含自定义比较器? -
@mjwills:不。我只是在寻找相同的键和值。不是字典的配置。
标签: c# dictionary code-generation