3

以下のコードを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#のこの簡略化されたメソッドは何と呼ばれますか。

PS:何と呼ばれているのかわからないので、この速記法の可用性をグーグルで検索できませんでした。それを呼ぶ名前はありますか?

4

6 に答える 6

10

This is an object initializer, which also exists in VB:

New DemoUsers With { .UserName = "name1", .UserAddress = "Address1" }

Note that your C# could be even cleaner if you also use a collection initialzer:

var users = new List<DemoUsers>
{
    new DemoUsers { UserName = "name1", UserAddress = "Address1" }
};

And yes, collection initializers exist in VB too.

于 2012-11-01T14:43:59.933 に答える
5

You could take a look at the With keyword:

Dim usr1 As New DemoUsers()

With usr1
    .UserName = "name1"
    .UserAddress = "Address1"
End With

You can also use this in an object initializer:

Dim usr1 As New DemoUsers With { .UserName = "name1", 
                                 .UserAddress = "Address1" }
于 2012-11-01T14:42:30.293 に答える
4
Dim users As New List(Of DemoUsers)()
users.Add(New DemoUsers() With { _
    Key .UserName = "name1", _
    Key .UserAddress = "Address1" _
})

I used http://www.developerfusion.com/tools/convert/csharp-to-vb/

于 2012-11-01T14:41:24.400 に答える
1

This is using a feature called Object Initializer.

See this SO answer regarding object initializers in VB.Net.

于 2012-11-01T14:43:53.147 に答える
0

It's called an object initializer:

Dim cust1 As New Customer With {.Name = "Toni Poe", 
                                .City = "Louisville"}
于 2012-11-01T14:41:32.173 に答える
0

Its called object initializer syntax.

In VB

Dim usr1 As New DemoUsers() With
{
    .UserName = "name1",
    .UserAddress = "Address1"
}
于 2012-11-01T14:43:20.397 に答える