我想知道是否有一种方法可以在VB中编写以下代码。 (现在等效的VB.NET代码看起来太冗长了)
List<DemoUsers> users = new List<DemoUsers>();
users.Add(new DemoUsers
{
UserName = "name1",
UserAddress = "Address1"
});
现在我正在用VB.NET编写
Dim users As New List(Of DemoUsers)
Dim usr1 As New DemoUsers()
usr1.UserName = "name1"
usr1.UserAddress = "Address1"
users.Add(usr1)
VB.NET是否具有等效的C#简写?这也是C#中这个简短的方法。
P.S:无法谷歌这个简短的符号可用性,因为我不知道它叫什么。有名称可以称之为吗?
答案 0 :(得分:10)
这是object initializer,also exists in VB:
New DemoUsers With { .UserName = "name1", .UserAddress = "Address1" }
请注意,如果您还使用集合初始值,那么您的C#可能更清晰:
var users = new List<DemoUsers>
{
new DemoUsers { UserName = "name1", UserAddress = "Address1" }
};
答案 1 :(得分:5)
您可以查看With
keyword:
Dim usr1 As New DemoUsers()
With usr1
.UserName = "name1"
.UserAddress = "Address1"
End With
您也可以在object initializer:
中使用此功能Dim usr1 As New DemoUsers With { .UserName = "name1",
.UserAddress = "Address1" }
答案 2 :(得分:4)
Dim users As New List(Of DemoUsers)()
users.Add(New DemoUsers() With { _
Key .UserName = "name1", _
Key .UserAddress = "Address1" _
})
我使用了http://www.developerfusion.com/tools/convert/csharp-to-vb/
答案 3 :(得分:1)
这是使用名为Object Initializer的功能。
请参阅以下有关object initializers in VB.Net的答案。
答案 4 :(得分:0)
它被称为object initializer:
Dim cust1 As New Customer With {.Name = "Toni Poe",
.City = "Louisville"}
答案 5 :(得分:0)
它被称为对象初始化语法。
在VB中
Dim usr1 As New DemoUsers() With
{
.UserName = "name1",
.UserAddress = "Address1"
}