在 VB.NET 中将未知结构转换为无类型对象

Convert an unknown structure to an untyped Object in VB.NET

我想将未知的基本结构转换为对象(此处无类型)。

我正在构建一个库,许多用户将使用它从我的系统中提取数据,但不想为他们中的每个人做一个新功能。他们必须知道结果会怎样。

在 vb 中,可以创建一个具有某些属性的对象并将其用作常规 Class,如下所示:

Dim myObj as New With { .name = "Matt", .age = "28" }
MsgBox( myObj.name & " is now " & myObj.age & " years old.")

到目前为止,还不错。

下一步:我的用户会给我一些说明,我需要从各种数据库中提取数据,但我不知道结果会是什么。

执行后我知道的是一个字符串列表,其中包含结果集的列,当然还有(一组)行。

这当然是问题所在

到目前为止我的函数(单行):

Public Function GetData(ByVal instructions as String) as Object ' User is supposed to know what will be inside, instructions is as XML describing DB, table, query, ...
   ' Do what is needed to retrieve data
   ' Here I have a variable cols As List(Of String) ' e.g. ("BP", "NAME", "VAT")
   Dim o As New With ???
   Return o
End Function

我试过的方法:即时构建一个假的 JSon,并尝试反序列化为对象。 但即使它看起来有效,我(和用户)也无法访问 属性,就像我最上面的代码一样:

MsgBox(o.BP)

我知道我可以做到

Public Function GetData(Of T As {New})(ByVal instructions as String) As T
   Dim o As T
   ' Use some Reflexion to TryInvokeMember of T
   Return o
End Function

但我想消除创建 class 来使用我的代码的麻烦。 另外,我的图书馆将在网络服务中使用,然后用户的 class 是未知的。

一种方法可能是 - 使用 Dictionary(Of String, Object)

Public Function GetData(instructions as String) As Dictionary(Of String, Object)
    Dim data = ' Load data
    Dim columns As String() = { "BP", "NAME", "VAT" }

    Return columns.ToDictionary(
        Function(column) column,
        Function(column) data.GetByColumnName(column)
    )
End Function

` Usage

Dim result = GetDate("instructions: ['BP', 'NAME']")
' Because user knows it is Integer
Dim bpValue = DirectCast(result.Item("BP"), Integer)

感谢@GSerg、@Fabio 和其他一些关于 ExpandoObject 的搜索,我做到了!

Imports System.Dynamic  

Dim o As Object = New ExpandoObject()
For Each col In cols
    DirectCast(o, IDictionary(Of String, Object)).Add(col, row.GetString(col))
Next