直接通过对象初始化器填充数组 [英] Populate array directly through object initializer
问题描述
我有这两个类:
class Customer
{
public string Name;
public string City;
public Order[] Orders;
}
class Order
{
public int Quantity;
public Product Product;
}
然后在 Main
我执行以下操作:
And then in the Main
I do the following:
Customer cust = new Customer
{
Name = "some name",
City = "some city",
Orders = {
new Order { Quantity = 3, Product = productObj1 },
new Order { Quantity = 4, Product = productObj2 },
new Order { Quantity = 1, Product = producctObj3 }
}
};
但是我无法使用集合初始化程序初始化数组 ...
。
而且我知道这是可行的,即 string [] array = { A, B};
在我看来是一样的。
But I cannot initialize the array ... with a collection initializer
.
And I know that this, i.e., is possible string[] array = { "A" , "B" };
which looks the same to me...
当然,我可以制作 Order
的单独对象,将它们放入数组中,然后将其分配给 Orders
,但我不喜欢这个主意。
Of course I could make separate objects of Order
, put them in an array and then assign it toOrders
, but I don't like the idea.
在这种情况下,如何获得简洁且代码较少的解决方案?
How can I achieve the clean and less-code-solution in this case?
推荐答案
C#不提供用于对象初始化的JSON样式表示法,因为它是高度静态类型的语言,不使用积极的类型推断。您必须在使用初始化代码之前调用数组构造函数( new Order []
):
C# does not provide JSON style notation for object initialization, because it is strongly statically typed language, that does not use aggressive type inference. You have to call array constructor(new Order[]
) before using initializer code:
Customer custKim = new Customer
{
Name = "some name",
City = "some city",
Orders = new Order[]{
new Order { Quantity = 3, Product = productObj1 },
new Order { Quantity = 4, Product = productObj2 },
new Order { Quantity = 1, Product = producctObj3 }
}
};
这篇关于直接通过对象初始化器填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!