【发布时间】:2014-11-23 00:30:51
【问题描述】:
我有这两个类:
class Customer
{
public string Name;
public string City;
public Order[] Orders;
}
class Order
{
public int Quantity;
public Product Product;
}
然后在Main 中我执行以下操作:
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 }
}
};
但我无法初始化数组... with a collection initializer。
而且我知道这是可能的string[] array = { "A" , "B" };,在我看来是一样的......
当然,我可以制作Order 的单独对象,将它们放在一个数组中,然后将其分配给Orders,但我不喜欢这个主意。
在这种情况下,我怎样才能实现干净且代码更少的解决方案?
【问题讨论】:
-
您没有正确使用初始化程序:使用
Orders = new [] { }表示您正在初始化一个数组。
标签: c# arrays object-initializers