VB.net对象初始化程序数组对象

时间:2019-04-01 19:49:13

标签: asp.net-mvc vb.net model-view-controller

我正在尝试使用对象初始化程序在vb.net中设置自定义数组,该数组的任何给定实例上可能只有1个条目,或者可能有100个条目。我已经在C#中成功完成了此任务,但是在Vb.net中找不到完成该任务的文档

我有一个模特:

Public Class Artist
    Public Name As String
    Public Task As String
End Class

在另一个模型中,我们进一步将此对象列为集合的一部分

    Public Property Artists() As Artist

这使我进入了控制器

            .Artists = New Artist() With
            {.Name = "bob", .Task = "1"}

成功进入1次;我将如何在对象的同一实例下添加另一个条目,例如c#

中的以下内容
Artists = new Artist[]
{
    new Artist() { name = "bob", Task = "1" },
    new Artist() { name = "fred", Task = "2" },
    new Artist() { name = "george", Task = "3" }
}

所有这些都属于with语句,而with语句本身是另一个对象的子对象,这似乎排除了传统的尺寸标注

    Dim cB = New CB {
        .StoryTitle = "Test"
        .IsbnNumber = 200
        .Artists = new Artists...
}

最终解决方案

    Dim cB = New CB With {
        .StoryTitle = "Test",
        .IsbnNumber = 200,
        .Artists = New Artist() {New Artist() With {
    .Name = "bob",
    .Task = "1"
}, New Artist() With {
    .Name = "fred",
    .Task = "2"
}, New Artist() With {
    .Name = "george",
    .Task = "3"
}}
    }

2 个答案:

答案 0 :(得分:0)

您的语法有些偏离。试试这个:

    Dim artists() As Artist = {
        New Artist() With {.Name = "bob", .Task = "1"},
        New Artist() With {.Name = "bob", .Task = "1"}
    }

答案 1 :(得分:0)

  

我已经在C#中成功完成了此任务,但是在Vb.net中找不到完成该任务的文档

下载ILSpy,拖放使用C#成功创建的Exe或Dll,然后将项目另存为VB.Net项目。

我会使用C#和VB.Net进行双语操作,但是当涉及到VB.Net中的Lambda和LINQ时,这就是我在两种语言之间进行翻译的方式。

或更简单,更快捷的方法是:http://converter.telerik.com/

C#:

Artists a = new Artist[]
{
    new Artist() { name = "bob", Task = "1" },
    new Artist() { name = "fred", Task = "2" },
    new Artist() { name = "george", Task = "3" }
}

VB.Net:

Dim a As Artists = New Artist() {New Artist() With {
    .name = "bob",
    .Task = "1"
}, New Artist() With {
    .name = "fred",
    .Task = "2"
}, New Artist() With {
    .name = "george",
    .Task = "3"
}}