【问题标题】:CodeDom and collection initializersCodeDom 和集合初始化器
【发布时间】:2011-03-04 04:25:32
【问题描述】:

有没有办法使用 C# CodeDom 生成字典初始化程序?那些都支持吗?

我想要:

private IDictionary<string, string> map = new Dictionary<string, string>
{
    { "Name", "Value" },
    ...
};

【问题讨论】:

    标签: c# code-generation codedom object-initializers


    【解决方案1】:

    使用 CodeDom 构造是不可能的。它们没有针对集合初始化程序进行更新。

    LukeH 有一篇关于 3.5 特性和 CodeDom 主题的优秀博文

    【讨论】:

    • 恐怕是这样...还是谢谢!
    • 上面链接的博客文章解释说 CodeDom 没有针对“新”C# 3.0 功能进行更新,并给出了使用 CSharpCodeProvider.CompileAssemblyFromSource 编译包含 LINQ 表达式的代码字符串的示例。
    【解决方案2】:

    你可以做到,但这可能是有史以来最糟糕的噩梦。这就是我目前的做法。 (更新了我的答案以反映问题)

    var constructDictionary = new CodeMemberField("Dictionary<string, string> map", @" = new Dictionary<string, string>()
    {
       { Name, Value },
    }");
    

    这也可以再次填充它的hackish。

    string builder += " = new Dictionary<string, string>(){";
    for(int i = 0; i < 10; i++)
    {
       builder+="{ Name"+i+", Value"+i+" }";
    }
    var constructDictionary = new CodeMemberField("Dictionary<string, string> map", builder+" }");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-05
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多