2013-04-30 43 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

相关问题