类 中的 C# 数组

C# Arrays in Classes

有了这些 class。我将如何添加一个包含几个组件的新小部件? Component 不能是 List,因为现实世界的模型来自具有该结构的 Web 服务。我已经使用 List 完成了此操作,但是当我尝试将 'Widget' class 添加到链上更远的模型时,它无法按预期工作

public class Widget
{
  public int Id {get; set; }
  public string Name { get; set; }
  public Part[] parts { get; set; }
}

public class Part
{
  public int Id { get; set; }
  public string Name { get; set; }
}

Widget widget = new Widget {
  Id = 1,
  Name = TheWidget
};


foreach(var c in SomeArray)
{
  Part part = new Part()
  {
    component.Id = c.Id,
    component.Name = c.Name
  }
  // Add component to widget
  
}

如果您想坚持现有的 Widget 实现,您可以创建一个 List<Part>,然后将其转换为数组:

using System.Linq;

...

List<Part> list = new List<Part>();

foreach(var c in SomeArray)
{
  Part part = new Part()
  {
    Id = c.Id,
    Name = c.Name
  }

  // Add component to a list, not widget (we can't easily add to array)
  list.Add(part);
}

// Having all parts collected we turn them into an array and assign to the widget
widget.parts = list.ToArray();

Linq 会更短:

widget.parts = SomeArray
  .Select(c => new Part() {
     Id = c.Id,
     Name = c.Name
   })
  .ToArray(); 

更好的方法是更改​​Widget:让我们将零件收集到列表中,而不是数组

public class Widget
{
  public int Id {get; set; }
  public string Name { get; set; }
  public List<Part> Parts { get; } = new List<Part>();
}

那么你可以把

foreach(var c in SomeArray)
{
  Part part = new Part()
  {
    Id = c.Id,
    Name = c.Name
  }

  // Add component to widget
  widget.Parts.Add(part);
}