c# - 我可以在 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
}
};
}
}
解决方案
像这样使用 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()
}
推荐阅读
- multithreading - 减少导致高 CPU 的特定进程的线程数
- json - 从字典中获取键
- java - 使用 Mockito 测试我的 SpringBoot 应用程序时如何从属性文件中传递变量?
- javascript - 如何将下拉选择更新为“已选择”onClick
- php - 如何获取 PHP 标签之间的函数的 HTML 内容?
- asp.net - AKS 中的 Web.API,许可证
- java - Spring JmsTemplate 目的地特定的消息持久性
- javascript - 为什么文件输入更改不能重复工作?
- javascript - 基于删除线(和背景颜色)的 Google 表格计数单元格
- python - 为什么我的多处理代码停止处理大型数据集?