首页 > 解决方案 > 我可以在 c# cSharp 中构造期间动态填充对象中的数组属性吗

问题描述

在 C# 中,在初始化对象期间,开发人员能够在不使用特定构造函数签名的情况下指定属性值,我想知道是否可以使用 foreach 循环填充具有动态条目数的数组属性(或其他一些动态循环方法)。

例如...

public class MyObject
{
    public string[] ArrayOfItems { get; set; }
    public MyObject()
    {

    }
}

public class Item
{
    public string ItemName { get; set; }
    public Item()
    {

    }
}

public void CreateNewMyObject()
{
    //List would normally come from elsewhere...
    List<Item> ItemList = new List<Item>()
    {
        new Item() { ItemName = "Item One" },
        new Item() { ItemName = "Item Two" },
        new Item() { ItemName = "Item Three" }
    };

    MyObject myObject = new MyObject()
    {
        ArrayOfItems = new string[]
        {
            //  This is where I'm stuck.
            //  I want to dynamically build my array but cant use foreach?
            foreach (Item item in ItemList)
            {
                item.ItemName
            }
        };
    }
}

标签: c#arrays

解决方案


像这样使用 LINQ:

MyObject myObject = new MyObject()
{
    ArrayOfItems = ItemList.Select(i => i.ItemName).ToArray()
}

如果ArrayOfItems是复杂类型,例如MyArrayItem,并且Item有一个额外的ItemCost属性,你会这样做:

MyObject myObject = new MyObject()
{
    ArrayOfItems = ItemList.Select(i => new MyArrayItem() { Name = i.ItemName, Cost = i.ItemCost }).ToArray()
}

并且应该MyArrayItem有一个匹配的构造函数:

MyObject myObject = new MyObject()
{
    ArrayOfItems = ItemList.Select(i => new MyArrayItem(i.ItemName, i.ItemCost)).ToArray()
}

推荐阅读