将类实例转换为字典和反之亦然

时间:2018-01-30 21:57:29

标签: vb.net dictionary

我们说我有班级

Sync

我希望将此类的实例转换为字典,其中键是变量名称,值是其值。我该怎么做?

另外,我们说我有字典

Class foo()
    public bar as string
    public bar2 as string
end class

并希望将其转换为类的实例" foo"以上。我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用Reflection,你可以做你要求的两件事。这适用于包含Properties和Fields的类(因为您的示例有Fields)。

Imports System.Reflection

Module Module1

    Sub Main()
        Dim myFoo As New foo With {.bar = "barValue", .bar2 = "bar2Value"}
        Dim myDictionary = InstanceToDictionary(myFoo)
        Dim myNewFoo = DictionaryToInstance(Of foo)(myDictionary)
    End Sub

    Public Function InstanceToDictionary(Of T)(instance As T) As Dictionary(Of String, Object)
        Dim result As New Dictionary(Of String, Object)()
        For Each pi As PropertyInfo In GetType(T).GetProperties
            result.Add(pi.Name, pi.GetValue(instance))
        Next
        For Each fi As FieldInfo In GetType(T).GetFields
            result.Add(fi.Name, fi.GetValue(instance))
        Next
        Return result
    End Function

    Public Function DictionaryToInstance(Of T As New)(dictionary As IDictionary(Of String, Object)) As T
        Dim result As New T()
        For Each pi As PropertyInfo In GetType(T).GetProperties
            pi.SetValue(result, Convert.ChangeType(dictionary(pi.Name), pi.PropertyType), Nothing)
        Next
        For Each fi As FieldInfo In GetType(T).GetFields
            fi.SetValue(result, Convert.ChangeType(dictionary(fi.Name), fi.FieldType))
        Next
        Return result
    End Function

End Module

Class foo
    Public bar As String
    Public bar2 As String
End Class

enter image description here