字典初始化语法(C#)的说明 [英] Explanation of Dictionary Initialisation Syntax (C#)

查看:770
本文介绍了字典初始化语法(C#)的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现表明如下字典可以初始化一个例子:

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

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



我不明白语法 {猫,2} 有效期为创建一个键值对。集合初始化语法似乎是形式新MyObjType(){} ,而匿名对象的形式为 {a =A,B的=b} 。 ?什么是真正发生在这里。

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.

现在,您添加的项目,例如当 {猫,2} ,关键是猫。这将被equivilent给你做这样的事情, d.Add(猫,2); 。字典可以不放任何东西,从<字符串,字符串> < customClass,anotherCustomClass> 。 到 INT CAT价值 INT CAT = D [猫] >将2.这方面的一个例子是:

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

这篇关于字典初始化语法(C#)的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆