在VB.NET中等效于将T的对象添加到List(T)

时间:2012-08-07 12:46:33

标签: .net vb.net ienumerable

这是我的班级

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。

3 个答案:

答案 0 :(得分:6)

对于直接端口,请尝试

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

有关详情,请参阅Object Initializers: Named and Anonymous

答案 1 :(得分:1)

这是来自C#的正确直接转换,假设ServerName 实际上是已发布的String数组(请注意Servername初始化程序周围的额外大括号):

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

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

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

答案 2 :(得分:0)

您可以使用Enumerable初始化List(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"}})