创建新的类对象时将项目添加到IEnumerable <t>

时间:2018-07-06 07:59:59

标签: c# oop

我正在填充一个类,以期序列化为JSON

我的班级有字符串,第二个班级(IEnumerable中有一个Icons

public class ManifestModel
    {
        public string ShortName { get; set; }

        public string Name { get; set; }

        public IEnumerable<Icon> Icons { get; set; }

        public string BackgroundColour { get; set; }

        public string ThemeColour { get; set; }

        public class Icon
        {
            public string Src { get; set; }

            public string Type { get; set; }

            public string Sizes { get; set; }
        }
    }

创建ManifestModel实例时,很容易填充字符串属性,但是如何添加两个图标变量(icon192icon512)?

 var icon192 = new ManifestModel.Icon
            {
                Src = "192",
                Type = "images/png",
                Sizes = "192x192"
            };

 var icon512 = new ManifestModel.Icon
            {
                Src = "512",
                Type = "images/png",
                Sizes = "512x512"
            };

            var manifestModel = new ManifestModel
            {
                ShortName = siteRoot.GetValue<string>("siteTitle"),
                Name = siteRoot.GetValue<string>("siteName"),
                //how to add two Icon objects here
            };

我尝试过

3 个答案:

答案 0 :(得分:3)

只需创建一个数组并将其分配给Icons属性。

var manifestModel = new ManifestModel
{    
    Icons  = new[] { icon192, icon512 },
    //...

答案 1 :(得分:1)

由于IconsIEnumerable,因此您可以创建一个列表

var manifestModel = new ManifestModel
        {
            Icons = new List<ManifestModel.Icon>() { icon192, icon512 },    
            //do something 

答案 2 :(得分:0)

使用读/写属性维护对象中的项目列表并不常见。通常需要的是一种解决方案,您可以在其中编写:

foreach (Icon icon in model.Icons) {
    //Do something
}

具有读/写属性,Icons可以是null,结果将是NullReferenceException

更糟糕的是,您将添加潜在的细微错误。当您开始遍历Icons并在迭代过程中设置该值时,您可能希望您继续遍历新列表。但是,事实并非如此,您仍在迭代先前的值。通常,在这些情况下,原始迭代在继续时应失败并以InvalidOperationException结束。

为避免此问题,请使用从System.Collections.ObjectModel.Collection<T>派生的集合并将其公开为属性:

public class IconCollection : Collection<Icon> {
    //Customize here
}

public class ManifestModel
{
    //
    public IconCollection Icons { get; } = new IconCollection();
    //...
}

要添加项目时,您可以去:

model.Icons.Add(icon);

这将避免上述问题。

相关问题