开发者

Explanation of Dictionary Initialisation Syntax (C#)

I found an example showing that a dictionary can be initialised as follows:

Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat",开发者_StackOverflow中文版 2},
    {"dog", 1},
    {"llama", 0},
    {"iguana", -1}
};

I don't understand how the syntax {"cat", 2} is valid for creating a Key-Value Pair. Collection initialisation syntax seems to be of the form new MyObjType(){}, while anonymous objects are of the form {a="a", b="b"}. What is actually happening here?


Alright lets take a look at the code here:

Dictionary<string, int> d = new Dictionary<string, int>() 
{ 
    {"cat", 2}, 
    {"dog", 1}, 
    {"llama", 0}, 
    {"iguana", -1} 
};

a dictionary holds two things, a key, and a value. your declaration, Dictionary<string, int>, means the keys are strings, and the values are integers.

now, when your adding an item, for instance {"cat", 2},, the key is cat. this would be equivilent to you doing something like, d.Add("cat", 2);. a dictionary can hold anything, from <string, string> to <customClass, anotherCustomClass>. and to call it up you can use int CAT = d["cat"]; to which the value of int CAT would be 2. an example of this would be:

Dictionary<string, int> dict = new Dictionary<string, int>() 
{ 
    {"cat", 1}
};
dict.Add("dog", 2);
Console.WriteLine("Cat="+dict["cat"].ToString()+", Dog="+dict["dog"].ToString());

in in there, your adding cat and dog with different values and calling them up


Dictionary is an ICollection of KeyValuePairs. {"cat", 2} is a KeyValuePair.


I'm not really sure what your question is asking, but the answer is that this is the syntax for collection initialization that provides a shortcut to the Add method.

This works too, for example:

new List<DateTime>()
{
    {DateTime.Now},
    {new DateTime()},
    {DateTime.Now}
}

Usually when the question is "why is this valid", the answer is because "it is valid" :)

Note that the syntax you specified in the latter part of the question is not just for anonymous objects, its for any object with public property setters:

new MyPerson("Bob")
{
    Address = "185 What St",
    DoB = DateTime.Now
}


This is a key value pairing. The Dictionary<string,int> says the key will be a string and the value will be an int. Thus with {"cat", 2} you have a key of "cat" and a value of 2. Why you would have a key of cat and a value of 2, I am not sure, but never the less it is an example of a Dictionary<> with a string key and an int value. More info and examples can be found here:

MSDN Dictionary<> with Examples

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜