【问题标题】:How to Output a C# Dictionary as C# code?如何将 C# 字典输出为 C# 代码?
【发布时间】: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


【解决方案1】:

基于Gabe's answer上的一个相关问题,这里有一个扩展方法解决方案:

public static string ToCsharpString<TKey,TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> items) {
    StringBuilder str = new StringBuilder();

    string type_name = items.GetType().Name;
    int index = type_name.LastIndexOf('`');
    if (index == -1) {
        index = type_name.Length;
    }
    str.Append(type_name, 0, index);
    str.AppendFormat("<{0}, {1}>", typeof(TKey).Name, typeof(TValue).Name);
    str.Append(" {\n");

    foreach (var item in items) {
        str.AppendFormat("\t{{ {0}, {1} }},\n", ToLiteral(item.Key), ToLiteral(item.Value));
    }
    str.Append("}");

    return str.ToString(); 
}

static string ToLiteral(object obj) {
    string input = obj as string;
    if (input == null)
        return obj.ToString();

    // https://stackoverflow.com/a/324812/79125
    using (var writer = new StringWriter()) {
        using (var provider = CodeDomProvider.CreateProvider("CSharp")) {
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
            return writer.ToString();
        }
    }
}

输出略有不同,因为它打印的是框架类库类型而不是原始类型(Int32 而不是int),但效果很好:

Dictionary<Int32, String> {
    { 4, "a" },
    { 5, "b" },
}

Try it out.

改进空间:

  • 处理嵌入式字典上的递归(但由于防止无限递归的复杂性,我认为这不值得)。
  • 也许为非原始类型打印更好的东西?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2013-07-18
    • 2011-12-18
    • 1970-01-01
    相关资源
    最近更新 更多