可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Sorry if this is basic. I am a little new to C#, but why cant I add a Dictionary to the list of Dictionaries? The documentation I have looked up does it like this:
List<Dictionary<string, string>> data = new List<Dictionary<string, string>>(); data.Add(new Dictionary<string, string>() { "test", "" });
回答1:
When you create your Dictionary<string, string>
in the second line, you are not initializing it correctly.
What you need is this:
List<Dictionary<string, string>> data = new List<Dictionary<string, string>>(); data.Add(new Dictionary<string, string>() { {"test", ""} });
This creates a new key/value pair and adds it to the Dictionary. The compiler though you were trying to add an element called "test" and one called "" to the dictionary; which you can't do because those add operations require a value as well as a key.
回答2:
You are using the collection initializer for a list or array. A dictionary has keys and values, so it needs to have a set of parameters in braces:
data.Add( new Dictionary<string, string>() { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } } );
Initialize a Dictionary with a Collection Initializer
回答3:
Add extra {}
data.Add(new Dictionary<string, string>() { {"test", ""} });
Without extra brackets, you are trying to add two individual strings, "test"
and ""
, while you want to add a key-value pair.
回答4:
OK. The "List of Dictionaries" is probably over complicating the issue. You get the same error just with this line:
var x = new Dictionary<string, string>() { "test", "" };
The issue is populating a dictionary in this manner. If my example was changed to:
var x = new Dictionary<string, string>(); x.Add("test", "");
then going back to your original example, this will work:
List<Dictionary<string, string>> data = new List<Dictionary<string, string>>(); var x = new Dictionary<string, string>(); x.Add("test", "" ); data.Add(x);
BTW, why would you require a list of dictionaries. Sounds quite a compilcated design pattern to use - although technically valid.
回答5:
The dictionary object is expecting key and value, while you are only passing the key. When initializing a dictionary you need to do the following:
var anObject = new Dictionary<string, string>{ {"key", "value"} };
If initializing anObject with multiple items then it would be:
var anObject = new Dictionary<string, string> { { "key1", "val1" }, { "key2", "val2" } };
Hope that helps!