问题
Is there a way to generate a dictionary initializer using the C# CodeDom? Are those supported at all?
I would like to have:
private IDictionary<string, string> map = new Dictionary<string, string>
{
{ "Name", "Value" },
...
};
回答1:
This is not possible using the CodeDom constructs. They were not updated for collection initializers.
LukeH has an excellent blog post on the subject of 3.5 features and the CodeDom
- http://blogs.msdn.com/b/lukeh/archive/2007/07/11/c-3-0-and-codedom.aspx
回答2:
You can do it but its possibly the worst nightmare ever.. Here is how I am doing it currently. (Updated my answer to reflect the question)
var constructDictionary = new CodeMemberField("Dictionary<string, string> map", @" = new Dictionary<string, string>()
{
{ Name, Value },
}");
This can also be populated once again its 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+" }");
来源:https://stackoverflow.com/questions/3048691/codedom-and-collection-initializers