使用codedom在c#中编写代码

Aru*_*lam -1 c# codedom

我想生成用于创建哈希表对象的代码,并为其分配密钥和值编程.它应该类似于

Hashtable ht = new Hashtable();

ht.Add( "key1", "value1" );
ht.Add( "key2", "value2" );
ht.Add( "key3", "value3" );
Run Code Online (Sandbox Code Playgroud)

例如

CodeMemberMethod testMethod = new CodeMemberMethod();

        testMethod.Name = "Test" + mi.Name + "_" + intTestCaseCnt;
        testMethod.Attributes = MemberAttributes.Public;.....
Run Code Online (Sandbox Code Playgroud)

这里它创建了一个方法programacticaly现在我想创建一个哈希表,所以我问如何?

And*_*age 5

对于代码生成,请考虑文本模板转换工具包(T4)

这个模板......

Hashtable ht = new Hashtable();
<#
    foreach (var obj in DataSource)
    {
#>
ht.Add( "<#= obj.Key #>", "<#= obj.Value #>" );
<#
    }
#>
Run Code Online (Sandbox Code Playgroud)

...会产生这个输出......

Hashtable ht = new Hashtable();
ht.Add( "key1", "value1" );
ht.Add( "key2", "value2" );
ht.Add( "key3", "value3" );
...
ht.Add( "keyN", "valueN" );
Run Code Online (Sandbox Code Playgroud)

其中N是DataSource中的记录数.

最好的是,它内置于Visual Studio 2008中

我有很好的经验