如何在不使用匿名对象的情况下初始化列表初始值设定项中的对象
本文关键字:对象 列表 初始化 情况下 | 更新日期: 2023-09-27 18:37:22
我有一个列表,我使用初始值设定项列表对其进行了初始化,在该列表中,我想创建一个新对象,但我不希望该对象是匿名的。有人可以帮我吗?我的代码如下所示:
Product product=new Product(){
OrderProductAttributes = new List<OrderProductAttribute>
{
//initialize an object(I do not want it to be anonymous)
}
}
不确定这是否是匿名的意思,但您绝对可以在初始化期间进行具体的实例化。
Product product=new Product(){
OrderProductAttributes = new List<OrderProductAttribute>()
{
//initialize an object(I do not want it to be anonymous)
new OrderProductAttributes() { Property1 = 10, Property2 = false... },
new OrderProductAttributes() { Property1 = 20 Property2 = false... },
}};
您还可以命名变量并添加它们:
OrderProductAttributes test = new ...;
OrderProdcutAttributes test2 = new ...;
Product product=new Product(){
OrderProductAttributes = new List<OrderProductAttribute>()
{
//initialize an object(I do not want it to be anonymous)
test,
test2,
}};
注意 此代码需要位于实例化方法(例如构造函数)中,并且除非test
和test2
标记为static
,否则在成员声明中不起作用。