如何在 C# 中初始化 IEnumerable<CustomModel>?

尼兰詹

.NET 应用程序。我有这些课程:

public class Product
{
    public string BrandDescription { get; set; }
    public string StyleNumber { get; set; }

    public FamilyTree FamilyTree { get; set; }
    public DssProduct DssProduct { get; set; }

    public IEnumerable<OptionData> Options { get; set; }
}

public class OptionData
{
    public Guid Id { get; set; }

    public Colour PrimaryColour { get; set; }
    public Colour SecondaryColour { get; set; }

    public IEnumerable<SizeData> Sizes { get; set; }
}

public class Colour
{
    public string Name { get; set; }
}

我正在尝试向该模型添加一些示例数据,如下所示。

return new ProductMessageEvents()
        {
          Metadata = new KafkaProductEvent.Metadata
          {
            Timestamp = "test",
            Environment = "test"
          },
          Product = new KafkaProductEvent.Product
          {
            AgeGrading = "test",
            KeycodeType = "type1",
            FamilyTree = new KafkaProductEvent.FamilyTree
            {
              Class = new KafkaProductEvent.CodeNamePair
              {
                Code = "test code",
                Name = "test name"
              }
            },
            DssProduct = new KafkaProductEvent.DssProduct
            {
              DocumentStatus = "active"
            }
          },
          Version = "latestVersion"
        };

我试过如下。

Options = new OptionData[]
    {
      new OptionData
      {
        PrimaryColour = new Colour
        {
          Name = "White"
        }
      },
      new OptionData
      {
        PrimaryColour = new Colour
        {
          Name = "Green"
        }
      }
    }

我收到此错误:

无法将 ProductEvents.OptionData[] 类型隐式转换为 IList

在上面的代码中,我不确定如何将数据添加到选项。有人可以帮我将数据添加到 Option 字段的 IEnumerable 吗?任何帮助,将不胜感激。谢谢

帕特里克·霍夫曼

您可以使用任何实现 的类型IEnumerable<T>,例如 aList<T>或数组:

DssProduct = new KafkaProductEvent.DssProduct
{
  DocumentStatus = "active"
},
Options = new OptionData[]
{ new OptionData // fist option
    { Id = Guid.NewGuid()
    }
, new OptionData // second option
    { Id = Guid.NewGuid()
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章