VB.Net中的匿名类初始化

时间:2009-05-11 20:05:46

标签: c# vb.net anonymous-types

我想在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。

2 个答案:

答案 0 :(得分:18)

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。它被称为匿名类型。

答案 1 :(得分:8)

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