Answers:
这里有整页关于如何执行此操作的页面:
http://msdn.microsoft.com/en-us/library/bb531208.aspx
例:
在下面的代码示例中,a
Dictionary<TKey, TValue>
使用type的实例初始化StudentName
:
var students = new Dictionary<int, StudentName>()
{
{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};
请注意,从C#6开始,您现在可以按以下方式对其进行初始化
var students = new Dictionary<int, StudentName>()
{
[111] = new StudentName {FirstName="Sachin", LastName="Karnik", ID=211},
[112] = new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317},
[113] = new StudentName {FirstName="Andy", LastName="Ruth", ID=198}
};
清洁得多:)
希望它能完美运行。
Dictionary<string, double> D =new Dictionary<string, double>();
D.Add("String", 17.00);
.Add(int, "string")
将值添加到字典的方法。抱歉,这不能解决问题。
通常不建议这样做,但是在不确定的危机时期,您可以使用
Dictionary<string, object> jsonMock = new Dictionary<string, object>() { { "object a", objA }, { "object b", objB } };
// example of unserializing
ClassForObjectA anotherObjA = null;
if(jsonMock.Contains("object a")) {
anotherObjA = (ClassForObjA)jsonMock["object a"];
}