如何使用对象初始化设置属性做在vb.net数组创建 [英] How to do array creation in vb.net using object initializers to set properties

查看:316
本文介绍了如何使用对象初始化设置属性做在vb.net数组创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待在上的 http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

作为练习,我试图把它从C#转换成vb.net但与这片没有运气,

As an exercise, I'm trying to translate it from C# into vb.net but having no luck with this piece,

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



我试过

I tried

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

我见过的建议,用列表,而不是一个数组所以我要去尝试,但想知道我在这里失踪。

I've seen recommendations to use a List instead of an array so I'm going to try that but would like to know what I'm missing here.

推荐答案

看看对象初始化:

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

注意藏汉为'。'为每个要设置属性。

notice the With aswell as the '.' for each of the properties you want to set.

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

MSDN链接

进一步阅读。

这篇关于如何使用对象初始化设置属性做在vb.net数组创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆