Подтвердить что ты не робот

Анонимная инициализация класса в VB.Net

Я хочу создать анонимный класс в 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?"}}
                }
            };

ТНХ.

4b9b3361

Ответ 1

VB.NET 2008 не имеет конструктора new[], но VB.NET 2010 делает. Вы не можете создать массив анонимных типов непосредственно в VB.NET 2008. Трюк заключается в объявлении такой функции:

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

И пусть компилятор выводит для нас тип (так как это анонимный тип, мы не можем указать имя). Затем используйте его как:

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. Это не называется JSON. Он называется анонимным типом.

Ответ 2

В 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?"}}
  }
}