Anonymous classe di inizializzazione in VB.Net
-
21-08-2019 - |
Domanda
voglio creare una classe anonima in vb.net esattamente in questo modo:
var data = new {
total = totalPages,
page = page,
records = totalRecords,
rows = new[]{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}}
}
};
thx.
Soluzione
VB.NET 2008 non hanno la new[]
costrutto, ma VB.NET 2010 non. Non è possibile creare una vasta gamma di tipi anonimi direttamente in VB.NET 2008. Il trucco è quello di dichiarare una funzione come questa:
Function GetArray(Of T)(ByVal ParamArray values() As T) As T()
Return values
End Function
E hanno il compilatore dedurre il tipo per noi (visto che è tipo anonimo, non possiamo specificare il nome). Quindi utilizzarlo come:
Dim jsonData = New With { _
.total = totalPages, _
.page = page, _
.records = totalRecords, _
.rows = GetArray( _
New With {.id = 1, .cell = GetArray("1", "-7", "Is this a good question?")}, _
New With {.id = 2, .cell = GetArray("2", "15", "Is this a blatant ripoff?")}, _
New With {.id = 3, .cell = GetArray("3", "23", "Why is the sky blue?")}
) _
}
PS. Questo non si chiama JSON. Si chiama un tipo anonimo.
Altri suggerimenti
In VS2010:
Dim jsonData = New With {
.total = 1,
.page = Page,
.records = 3,
.rows = {
New With {.id = 1, .cell = {"1", "-7", "Is this a good question?"}},
New With {.id = 2, .cell = {"2", "15", "Is this a blatant ripoff?"}},
New With {.id = 3, .cell = {"3", "23", "Why is the sky blue?"}}
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow