繁体   English   中英

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

[英]How to declare anonymous class having data member dictionary type?

我在上课

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

您应该将keyvalue分开,例如:

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

注意花括号

如果您正在寻找字典属性的集合初始值设定项:

  attr = new Dictionary<string, object> {
            { "id",  "1" },
            { "title", "sdfsdf" },
            { "description", "asdasdasd" },
            { "rel",  "Folder" },
            { "parentID", DBNull.Value }
         }

字典的整个集合初始化程序都用大括号括起来。 内括号括起将要添加到Dictionary<string, object>键/值对的初始化程序。

我建议您阅读MSDN文章如何:使用集合初始化程序初始化字典


完整的代码应如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM