2014-09-28 49 views
1

我有這2類:填充陣列直接通過對象初始化

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,但我不不喜歡這個想法。

在這種情況下,我該如何實現清潔和代碼少的解決方案?

+4

你沒有正確使用的初始化:使用Orders = new [] {}'來表示你正在初始化一個數組。 – 2014-09-28 14:38:32

回答

3

C#不提供用於對象初始化的JSON樣式表示法,因爲它是強靜態類型的語言,不使用侵略式類型推斷。您可以選擇使用初始化代碼之前調用數組構造(new Order[]):

 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 } 
      } 
     }; 
4

吉榮和尤金提供了一些很好的選擇,但事實是,你CAN使用您在說明書中提供的語法,如果你使用泛型列表,集合和其他類型,但不能用簡單的數組。

因此,如果你定義你的客戶類爲:

class Customer 
{ 
    public Customer() 
    { 
     Orders = new List<Order>(); 
    } 

    public string Name; 
    public string City; 
    public List<Order> Orders; 
} 

您可以使用您想在第一時間使用的語法:

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 } 
    } 
};