我正在上课
public class Person
{
public string Name;
public Dictionary<string, object> attr;
public string state = "closed";
}
我想将数据添加到List
List<Person> mPer = new List<Person>();
mPer.Add(new Person() { data = "My tasks" },attr = new Dictionary<string, object>() {id= "1",title = "sdfsdf",description = "asdasdasd",rel = "Folder",parentID = DBNull.Value});
答案 0 :(得分:3)
您应该将key
和value
分开,例如:
attr = new Dictionary<string, object>() { { key, { value } };
在你的情况下:
attr = new Dictionary<string, object>() { { "myKey", new { id = 2, ... } };
如果您想添加多个项目:
attr = new Dictionary<string, object>() {
{ "myKey", new {id = 2, title = "sdfsdf", description = "asdasdasd"} },
{ "myOtherKey", new {id = 3, title = "sdfsdsdf", description = "asdaasdasd" } }
};
请注意花括号
答案 1 :(得分:1)
如果您正在为词典属性寻找collection initializer:
attr = new Dictionary<string, object> {
{ "id", "1" },
{ "title", "sdfsdf" },
{ "description", "asdasdasd" },
{ "rel", "Folder" },
{ "parentID", DBNull.Value }
}
字典的整个集合初始化程序用大括号括起来。内括号包含将添加到Dictionary<string, object>
的键/值对的初始值设定项。
我建议您阅读MSDN文章How to: Initialize a Dictionary with a Collection Initializer
完整代码应如下所示:
mPer.Add(new Person {
Name = "My tasks", // no braces here
attr = new Dictionary<string, object> {
{ "id", "1" },
{ "title", "sdfsdf" },
{ "description", "asdasdasd" },
{ "rel", "Folder" },
{ "parentID", DBNull.Value }
}
});