2013-04-30 75 views
2

我看的代碼示例上http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api如何使用對象初始化設置屬性

作爲練習,我試圖把它從C#轉換成vb.net做在vb.net數組創建,但有這片沒有運氣,

public class Product 
     { 
      public int Id { get; set; } 
      public string Name { get; set; } 
      public string Category { get; set; } 
      public decimal Price { get; set; } 
    } 
    Product[] products = new Product[] 
     { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
     new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
     new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
      }; 

我試圖

 Public class Product 
     Public Property Id As Integer 
     Public Property Name As String 
     Public Property Category As String 
     Public Property price As Decimal 
     End Class 

    Dim products() As Product = { _ 
     new Product (Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1), _ 
     new Product (Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M), _ 
     new Product (Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M) } 

我見過建議使用一個列表,而不是一個數組的所以我要去嘗試,但想知道w ^我在這裏失蹤的帽子。

+0

[這](http://stackoverflow.com/questions/291413/how-to-declare-an-array-inline-in-vb-net)可能會有所幫助,尤其是Jon Skeet的回答與你在這裏的回答有些不同。 – Cemafor 2013-04-30 17:23:53

+0

我問題的數組公式或創建新的'Product's? – Cemafor 2013-04-30 17:27:48

回答

9

看看對象初始化:

Dim namedCust = New Customer With {.Name = "Terry Adams"..... 

通知With藏漢作爲 ''爲您要設置的每個屬性。

Dim products() As Product = { _ 
     new Product With {.Id = 1, .Name = "Tomato Soup", .Category = "Groceries", 
          .Price = 1 }, _..... 

MSDN Link

Further reading.

+0

完美!謝謝 – oldDavid 2013-05-01 18:26:17

+0

不用擔心。如果那是你以後的事情,請標記爲答案。 – Ric 2013-05-01 19:41:17

相關問題