C# 使用CodeDom构建词典

C# 使用CodeDom构建词典,c#,codedom,C#,Codedom,我正试图找到一种使用CodeDom构建类似这样的东西的方法 public System.Collections.Generic.Dictionary<string, string> Attributes { get { return new System.Collections.Generic.Dictionary<string, string>() { {"firstkey", "first val

我正试图找到一种使用CodeDom构建类似这样的东西的方法

public System.Collections.Generic.Dictionary<string, string> Attributes
{
    get
    {
        return new System.Collections.Generic.Dictionary<string, string>()
        {
            {"firstkey", "first value"},
            {"second", "second value"},
            {"third", "third value"}
        };
    }
}
public System.Collections.Generic.Dictionary属性
{
得到
{
返回新的System.Collections.Generic.Dictionary()
{
{“第一个键”,“第一个值”},
{“第二个”、“第二个值”},
{“第三”、“第三值”}
};
}
}
我确实读过这篇文章,但它并没有真正把我带到我想去的地方

是我干的

Type myType = typeof (System.Collections.Generic.Dictionary<string, string>);
string dictionaryTypeName = myType.FullName;

CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName);

var abc = new CodeVariableDeclarationStatement(
    dictionaryType, "dict2",
    new CodeObjectCreateExpression(
        dictionaryType, new CodeSnippetExpression(@"{""firstkey"", ""first value""}")
        )
    );

property.GetStatements.Add(abc);
Type myType=typeof(System.Collections.Generic.Dictionary);
字符串字典TypeName=myType.FullName;
CodeTypeReference dictionaryType=新的CodeTypeReference(dictionaryTypeName);
var abc=新的CodeVariableDeclarationStatement(
dictionaryType,“dict2”,
新的CodeObjectCreateExpression(
dictionaryType,新的代码片段表达式(@“{”“firstkey”“first value”“}”)
)
);
property.GetStatements.Add(abc);
它产生了这个

public Dictionary<object, object> Attributes
{
    get
    {
        Dictionary<string, string> dict2 = new Dictionary<string, string>({"firstkey", "first value"});
    }
}
public System.Collections.Generic.Dictionary<string, string> Attributes
{
    get
    {
        System.Collections.Generic.Dictionary<string, string> dict = new System.Collections.Generic.Dictionary<string, string>();
        dict.Add("a", "xx xx1");
        dict.Add("b", "xx xx2");
        dict.Add("c", "xx xx3");
        return dict;
    }
}
公共字典属性
{
得到
{
Dictionary dict2=新字典({“firstkey”,“first value”});
}
}

任何构建类似东西的人?

我都必须使用。添加,而不是将值作为参数添加到构造函数中

if (type == typeof(Dictionary<string, string>))
{
    string variableName = "dict";

    CodeVariableDeclarationStatement codeVariableDeclarationStatement = new CodeVariableDeclarationStatement(new CodeTypeReference(type.FullName), variableName,
            new CodeObjectCreateExpression(type)
    );

    property.GetStatements.Add(codeVariableDeclarationStatement);
    property.GetStatements.Add(AddPropertyValues(new CodeSnippetExpression(string.Format(@"""{0}"", ""{1}""", "a", "xx xx1")), variableName));
    property.GetStatements.Add(AddPropertyValues(new CodeSnippetExpression(string.Format(@"""{0}"", ""{1}""", "b", "xx xx2")), variableName));
    property.GetStatements.Add(AddPropertyValues(new CodeSnippetExpression(string.Format(@"""{0}"", ""{1}""", "c", "xx xx3")), variableName));

    property.GetStatements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression(variableName)));
}

static CodeStatement AddPropertyValues(CodeExpression exp, string variableReference)
{
    return new CodeExpressionStatement(
        new CodeMethodInvokeExpression(
            new CodeMethodReferenceExpression(
                new CodeTypeReferenceExpression(new CodeTypeReference(variableReference)),
                    "Add"),
                        new CodeExpression[]{
                            exp,
                                }));
}
if(type==typeof(字典))
{
字符串variableName=“dict”;
CodeVariableDeclarationStatement CodeVariableDeclarationStatement=新的CodeVariableDeclarationStatement(新的CodeTypeReference(type.FullName)、variableName、,
新的CodeObjectCreateExpression(类型)
);
添加(codeVariableDeclarationStatement);
Add(addPropertyValue(新的代码段表达式(string.Format(@“{0}”、“{1}”)、“a”、“xx xx1”)、variableName);
Add(addPropertyValue(新的代码段表达式(string.Format(@“{0}”、“{1}”)、“b”、“xx xx2”)、variableName);
Add(addPropertyValue(新的代码段表达式(string.Format(@“{0}”、“{1}”)、“c”、“xx xx3”)、variableName);
Add(新的CodeMethodReturnStatement(新的CodeSnippetExpression(variableName));
}
静态CodeStatement AddPropertyValue(CodeExpression,string variableReference)
{
返回新的CodeExpressionStatement(
新的CodeMethodInvokeeExpression(
新的CodeMethodReferenceExpression(
新的CodeTypeReferenceExpression(新的CodeTypeReference(variableReference)),
“添加”),
新的代码表达式[]{
经验,
}));
}
产生这个

public Dictionary<object, object> Attributes
{
    get
    {
        Dictionary<string, string> dict2 = new Dictionary<string, string>({"firstkey", "first value"});
    }
}
public System.Collections.Generic.Dictionary<string, string> Attributes
{
    get
    {
        System.Collections.Generic.Dictionary<string, string> dict = new System.Collections.Generic.Dictionary<string, string>();
        dict.Add("a", "xx xx1");
        dict.Add("b", "xx xx2");
        dict.Add("c", "xx xx3");
        return dict;
    }
}
public System.Collections.Generic.Dictionary属性
{
得到
{
System.Collections.Generic.Dictionary dict=新的System.Collections.Generic.Dictionary();
添加(“a”,“xx xx1”);
添加(“b”,“xx xx2”);
添加(“c”,“xx xx3”);
返回命令;
}
}

很公平

如果您想使用初始化而不是Add方法,那么对于构造函数的调用也必须使用Snippet方法。如果您不想将类型名写入常量字符串,那么这可能会更困难。在这种情况下,您可以创建对无参数构造函数的调用,使用CSharpCodeProvider获取表示构造函数调用的字符串,扔掉最后的括号并连接初始化片段。代码如下所示,并生成所需的代码:

        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        CodeGeneratorOptions options = new CodeGeneratorOptions();
        options.IndentString = "   ";
        options.BracingStyle = "C";

        Type myType = typeof(System.Collections.Generic.Dictionary<string, string>);
        string dictionaryTypeName = myType.FullName;

        CodeTypeReference dictionaryType = new CodeTypeReference(dictionaryTypeName);

        // here you create the CodeobjectCreateExpression in order to obtain the string with the name of the type
        StringWriter sw = new StringWriter();
        CodeObjectCreateExpression createExpr = new CodeObjectCreateExpression(dictionaryType);
        codeProvider.GenerateCodeFromExpression(createExpr, sw, options);
        string creationCode = sw.ToString();
        // throw away the final ()
        creationCode = creationCode.Substring(0, creationCode.Length - 2);
        // add initialization
        creationCode = creationCode + @"{{""firstkey"", ""first value""}, {""secondkey"", ""second value""}, {""thirdkey"", ""third value""}}";
        CodeMethodReturnStatement retVal = new CodeMethodReturnStatement(new CodeSnippetExpression(creationCode));
        property.GetStatements.Add(retVal);
CSharpCodeProvider codeProvider=新的CSharpCodeProvider();
CodeGeneratorOptions=new CodeGeneratorOptions();
options.IndentString=“”;
options.BracingStyle=“C”;
Type myType=typeof(System.Collections.Generic.Dictionary);
字符串字典TypeName=myType.FullName;
CodeTypeReference dictionaryType=新的CodeTypeReference(dictionaryTypeName);
//在这里创建CodeobjectCreateExpression,以获取具有类型名称的字符串
StringWriter sw=新的StringWriter();
CodeObjectCreateExpression createExpr=新的CodeObjectCreateExpression(dictionaryType);
generateCodeFromeExpression(createExpr、sw、选项);
string creationCode=sw.ToString();
//扔掉决赛()
creationCode=creationCode.Substring(0,creationCode.Length-2);
//添加初始化
creationCode=creationCode+@“{{”“第一个键”“第一个值”“},{”“第二个键”“第二个值”“},{”“第三个值”“}”;
CodeMethodReturnStatement retVal=新的CodeMethodReturnStatement(新的代码片段表达式(creationCode));
property.GetStatements.Add(retVal);