0

我试图找出一种方法来使用 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"}
        };
    }
}

我确实读过这个,但它并没有真正让我到达我想要的地方, http: //msdn.microsoft.com/en-us/library/system.codedom.codetypeparameter.aspx

我做了这个

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);

它生成这个

public Dictionary<object, object> Attributes
{
    get
    {
        Dictionary<string, string> dict2 = new Dictionary<string, string>({"firstkey", "first value"});
    }
}

有人建造过类似的东西吗?

4

2 回答 2

1

如果你想使用初始化而不是使用 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);
于 2012-09-19T12:43:05.743 回答
1

我确实必须使用 .add 而不是将值作为参数添加到构造函数中。

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,
                                }));
}

生成这个

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;
    }
}

很公平!

于 2012-09-19T09:47:12.307 回答