【问题标题】:How to do array creation in vb.net using object initializers to set properties如何使用对象初始化器在 vb.net 中创建数组以设置属性
【发布时间】:2013-04-30 17:17:41
【问题描述】:

我正在查看http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api 上的代码示例

作为一个练习,我正在尝试将它从 C# 翻译成 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 ) }

我看到了使用列表而不是数组的建议,所以我将尝试这样做,但想知道我在这里缺少什么。

【问题讨论】:

  • This 可能会有所帮助,尤其是 Jon Skeet 的回答与您在这里的回答有些不同。
  • 我是数组公式的问题还是创建新的Products?

标签: c# vb.net


【解决方案1】:

看看对象初始化器:

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.

【讨论】:

  • 不用担心。如果那是您所追求的,请标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-01
  • 2016-07-17
  • 2016-01-12
相关资源
最近更新 更多