Rag*_*ghu 0 c# dictionary instantiation type-conversion new-operator
Dictionary<string,object> dict = new Dictionary <string,object>();
Run Code Online (Sandbox Code Playgroud)
我可以dict用其他一些对象实例化" "吗?
例如:
dict = new Dictionary<string,bitmap>();
Run Code Online (Sandbox Code Playgroud)
要么:
dict = new Dictionary<string, Image>();
Run Code Online (Sandbox Code Playgroud)
不,因为Dictionary<string, object>并且Dictionary<string, Bitmap>是两种不同的类型.
想象一下在以下场景中会发生什么:
Dictionary<string, Bitmap> bmpDict = new Dictionary<string, Bitmap>();
Dictionary<string, object> dict = bmpDict;
dict.Add("someKey", 42);
Run Code Online (Sandbox Code Playgroud)
编译器必须编译它,因为dict输入的值是object,因此int是一个有效的选择.但是,这会与仅接受Bitmap值的实例化字典发生冲突:
Bitmap someBmp = bmpDict["someKey"];
Run Code Online (Sandbox Code Playgroud)
显然,值应该是Bitmap声明的和实例化的类型bmpDict,但正如我们在上面看到的那样,Bitmap通过dict变量添加了一些不是a的东西.如您所见,类型安全性将被打破.
因此,Dictionary<string, object>并Dictionary<string, Bitmap>不能相互分配.