2009-05-11 26 views
12

chcę utworzyć anonimowy klasy w vb.net dokładnie tak:Anonymous klasy inicjalizacji w Vb.NET

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.

+1

Twój przykład pokazuje anonimową klasę w C#, to nie jest związane z json .. –

+0

Kontekst za jego pytanie można znaleźć bardziej szczegółowo tutaj: http: // haacked. com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx –

Odpowiedz

17

VB.NET 2008 nie ma konstrukcji new[], ale VB.NET 2010 ma. Nie można utworzyć tablicę anonimowych typów bezpośrednio w VB.NET 2008. Sztuką jest, aby zadeklarować funkcję tak:

Function GetArray(Of T)(ByVal ParamArray values() As T) As T() 
    Return values 
End Function 

I mieć kompilator wywnioskować typ dla nas (ponieważ jest to typ anonimowy, nie możemy określić imię). Następnie użyj go:

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. Nie nazywa się to JSON. Nazywa się to anonimowym typem.

+0

Myślę, że to już nie jest prawda. –

+0

Zobacz http://stackoverflow.com/questions/3799403 – royco

+0

Nadal jest prawdą w przypadku VS2008 ;-) –

8

W 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?"}} 
    } 
} 
Powiązane problemy