我有一个列表,我使用一个初始化程序列表对其进行了初始化,并且在该列表中,我想创建一个新对象,并且我不希望该对象是匿名的。有人可以帮我吗?我的代码如下所示:
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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句