将New With从c#转换为VB.NET -编译错误

本文关键字:NET VB 编译 错误 转换 New With | 更新日期: 2023-09-27 18:18:13

我有以下c#代码:

public static ArrayList GetGenders()
{
    return new ArrayList()
    {
        new { Value = 1, Display = "ap" },
        new { Value = 2, Display = "up" }
    };
}

工作得很好。然而,当我把它转换成VB。净:

Public Shared Function GetGenders() As ArrayList
    Return New ArrayList() From { _
        New With { _
            .Value = 1, _
            .Display = "ap" _
        }, _
        New With { _
            .Value = 2, _
            .Display = "up" _
        } _
    }
End Function
我得到以下编译时错误:

BC30205: End of statement expected.

代码有什么问题?

将New With从c#转换为VB.NET -编译错误

我的通灵调试技能告诉我你在用VB。Net 2005,它不支持匿名类型

这可能是VB的一个版本。在2010年之前,在这种情况下,FROM语法是不可用的(我有同样的问题与一些代码转换由developerfusion -我是从c#在。Net 4到VB。.Net (.Net 3.5)

下面的两个步骤应该可以做到-还没有找到将其变成一行的方法:

Dim arr() = { _
    New With {.Value = 1, .Display = "ap"}, _
    New With {.Value = 2, .Display = "up"} _
}
return = New ArrayList(arr)

一个vb2005特有的答案包括创建一个类来保存这些值,然后用这个类的实例填充数组列表。

类:

Public Class LookupList
    Private m_Value As Integer
    Private m_sDisplay As String
    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub New(ByVal wValue As Integer, ByVal sDisplay As String)
        Me.New()
        Me.Value = wValue
        Me.Display = sDisplay
    End Sub
    Public Property Value() As Integer
        Get
            Return m_Value
        End Get
        Set(ByVal value As Integer)
            m_Value = value
        End Set
    End Property
    Public Property Display() As String
        Get
            Return m_sDisplay
        End Get
        Set(ByVal value As String)
            m_sDisplay = value
        End Set
    End Property
End Class

方法:

Public Shared Function GetGenders() As ArrayList
    Dim oList As New ArrayList
    oList.AddRange(New LookupList() {New LookupList(1, "ap"), New LookupList(2, "up")})
    Return oList
End Function

一个与原始c#代码更内联的解决方案是为类创建一个集合类:

Public Class LookupListCollection
    Inherits System.Collections.Generic.List(Of LookupList)
    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub New(ByVal ParamArray aItems As LookupList())
        Me.New()
        If aItems IsNot Nothing Then
            Me.AddRange(aItems)
        End If
    End Sub
End Class

,然后可以调用为:

Public Shared Function GetGenders() As LookupListCollection
    Return New LookupListCollection(New LookupList(1, "ap"), New LookupList(2, "up"))
End Function
lista.Add(New InvValorMedio With {.Data_Base = _dataBase, _
                                  .Tipo = item.IdInvTipo, _
                                  .Valor = 0})