I want to generate code for creating a hash table object and assigning it with a key and a value programmatic . it should be similar to
Hashtable ht = new Hashtable();
ht.Add( "key1", "value1" );
ht.Add( "key2", "value2" );
ht.Add( "key3", "value3" );
for eg
CodeMemberMethod testMethod = new CodeMemberMethod();
testMethod.Name = "Test" + mi.Name + "_" + intTestCaseCnt;
testMethod.Attributes = MemberAttributes.Public;.....
here it creates a method programmatically now I want to create a hashtable so I am asking how?
For code generation consider the Text Template Transformation Toolkit (T4)
This template...
Hashtable ht = new Hashtable();
<#
foreach (var obj in DataSource)
{
#>
ht.Add( "<#= obj.Key #>", "<#= obj.Value #>" );
<#
}
#>
...would generate this output...
Hashtable ht = new Hashtable();
ht.Add( "key1", "value1" );
ht.Add( "key2", "value2" );
ht.Add( "key3", "value3" );
...
ht.Add( "keyN", "valueN" );
Where N is the number of records in your DataSource.
The best thing is, this is built right into Visual Studio 2008
I have had good experiences with it
Where are you stuck? You know how to create a CodeMemberMethod, so you should be able to add statement objects to the CodeMemberMethod.Statements collection. You'll need one statement for the variable declaration, one for the assignment/initialization and one for each "Add"-Call.
BTW: I've used Code DOM in the past, but found that generating code directly with a templating engine is less works and makes the code far more readable. I usually use StringTemplate , and I'm very happy with it.
CodeParameterDeclarationExpression hashTableParam =new CodeParameterDeclarationExpression();
hashTableParam.Name = "hastable";
hashTableParam.Type = new CodeTypeReference(typeof(System.Collections.Hashtable));
this what i was looking for thanks for ur efforts
The two code generators I'm aware of are ...
Codesmith at ... main site , with a free version
T4 which is in Scott Hanselman has a blog post about it here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.