今天一朋友问我一个问题:怎样用集合初始设定项来初始化一个字典?他一直认为所谓集合初始设定项就是向一个类似List的容器中逐个添加数据,但是换成了字典一次需要两个数据,一下不知道怎么办……
我首先又一次强烈推荐他把MSDN当成解决一切问题的第一步尝试,其实集合初始值设定项MSDN里阐述得很透彻(地址:http://msdn.microsoft.com/zh-cn/library/bb384062.aspx ):集合初始值设定项就是连续调用一个IEnumerable类的Add函数。多个参数可以用{}(大括号)来分割。
那么初始化字典就是这样:
IDictionary<int, string> dic = new Dictionary<int, string>()
{
{23, "sfds"},
{434, "rg"},
{-3, "jif"}
};
foreach (KeyValuePair<int, string> pair in dic)
Console.WriteLine(pair);
输出:
[23, sfds]
[434, rg]
[-3, jif]
也可以自定义一个类继承IEnumerable并有Add函数
class a : System.Collections.IEnumerable
{
public void Add(object a, object b)
{
Console.WriteLine("Add被调用,a={0}, b={1}", a, b);
}
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
class Program
{
static void Main()
{
a obj = new a()
{
{1, "hehe"},
{DateTime.Now, Guid.NewGuid()}
};
}
}
输出:
Add被调用,a=1, b=hehe
Add被调用,a=6/23/2011 4:07:35 PM, b=73ecbf16-1cab-4aa6-af20-2afc9b622e67
当对一个非IEnumerable类使用集合初始设定项或一个IEnumerable类但没有Add函数,VS会产生编译错误。