Anonymous class initialization in VB.Net

后端 未结 2 1610
余生分开走
余生分开走 2021-02-13 22:05

i want to create an anonymous class in vb.net exactly like this:

var data = new {
                total = totalPages,
                page = page,
                      


        
2条回答
  •  旧巷少年郎
    2021-02-13 22:40

    VB.NET 2008 does not have the new[] construct, but VB.NET 2010 does. You cannot create an array of anonymous types directly in VB.NET 2008. The trick is to declare a function like this:

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

    And have the compiler infer the type for us (since it's anonymous type, we cannot specify the name). Then use it like:

    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. This is not called JSON. It's called an anonymous type.

提交回复
热议问题