1

这是我的课

Public Class DBServer
    Public  ServerId  As Integer
    Public  ServerName As String
End Class

和变量:

Dim serverList As New List(Of DBServer)

在 C# 中。我可以这样添加:

serverList.Add(new DBServer{ ServerId=1,ServerName="Server1"});

如何在 VB.NET 中实现这一点。我正在使用 .NET 4.0。

4

3 回答 3

6

对于直接端口,请尝试

serverList.Add(new DBServer With { .ServerId=1,.ServerName="Server1"})

有关更多信息,请参阅对象初始化器:命名和匿名

于 2012-08-07T12:49:59.870 回答
1

这是 C# 的正确直接翻译,假设它ServerName 实际上Servername是发布的字符串数组(注意初始化程序周围的额外花括号):

serverlist.Add(New DBServer() With {.ServerId = 1, .ServerName = {"foo"}})

如果 Servername不是字符串数组,实际上是字符串,那么 @Binary Worrier 有正确的解决方案:

serverlist.Add(New DBServer() With {.ServerId = 1, .ServerName = "foo"})
于 2012-08-07T12:59:56.460 回答
0

您可以使用 Enumerable (http://msdn.microsoft.com/en-us/library/fkbw11z0) 初始化列表

    Dim serverList As New List(Of DBServer)({New DBServer With {.ServerId = 1, .ServerName = "Server One"},
                                             New DBServer With {.ServerId = 2, .ServerName = "Server Two"},
                                             New DBServer With {.ServerId = 3, .ServerName = "Server Three"}})
于 2012-08-07T13:20:27.163 回答