Skip to main content
 首页 » 编程设计

c#之如何声明具有数据成员字典类型的匿名类

2024年02月13日15wayfarer

我在上课

public class Person 
{ 
    public string Name; 
    public Dictionary<string, object> attr; 
    public string state = "closed"; 
} 

我想将数据添加到列表中

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}); 

请您参考如下方法:

您应该将键和值分开,例如:

  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" } } 
        }; 

注意大括号