使用System.Type对象在运行时进行转换

时间:2015-07-31 16:32:49

标签: vb.net casting type-conversion runtime

我正在尝试创建一个带有DataRow的函数,并使用数据填充Object。

这是我的代码:

    Public Shared Sub PopulateObjectFromDatarow(ByVal obj As Object, ByVal drwRow As DataRow)
        Dim lstFields = obj.GetType() _
         .GetFields(BindingFlags.Instance Or BindingFlags.Public) _
         .ToList()
        For Each field As FieldInfo In lstFields
            If drwRow.Table.Columns.Contains(field.Name) Then
                field.SetValue(obj, drwRow.Field(Of Object)(field.Name))
            End If
        Next
    End Sub

它基本上将列名称与属性名称相匹配,并设置对象的属性值。这很有效,直到我点击Enum类型!

我在数据库中存储一个用于枚举值的整数,我需要能够将它转换回枚举值。

我可能值得一提的是我也在使用.Net3.5。

非常感谢任何帮助!

P.S。我已经尝试过这个了:

field.SetValue(obj, Convert.ChangeType(drwRow.Item(field.Name), field.FieldType))

无济于事......

1 个答案:

答案 0 :(得分:0)

在TnTinMin和Plutonix的评论之后,这是解决方案!

    Public Shared Sub PopulateObjectFromDatarow(ByVal obj As Object, ByVal drwRow As DataRow)
        Dim lstFields = obj.GetType() _
         .GetFields(BindingFlags.Instance Or BindingFlags.Public) _
         .ToList()
        For Each field As FieldInfo In lstFields
            If drwRow.Table.Columns.Contains(field.Name) Then
                If field.FieldType Is GetType(String) Then
                    field.SetValue(obj, HttpUtility.HtmlDecode(drwRow.Field(Of String)(field.Name)))
                ElseIf field.FieldType.IsGenericType Then
                    If drwRow.Field(Of Object)(field.Name) Is Nothing Then
                        field.SetValue(obj, Nothing)
                    Else
                        If field.FieldType.GetGenericArguments()(0).IsEnum Then
                            field.SetValue(obj, [Enum].Parse(field.FieldType.GetGenericArguments()(0), drwRow.Field(Of Integer)(field.Name).ToString()))
                        Else
                            field.SetValue(obj, drwRow.Field(Of Object)(field.Name))
                        End If
                    End If
                Else
                    If field.FieldType.IsEnum Then
                        field.SetValue(obj, [Enum].Parse(field.FieldType, drwRow.Field(Of Integer)(field.Name).ToString()))
                    Else
                        field.SetValue(obj, drwRow.Field(Of Object)(field.Name))
                    End If
                End If
            End If
        Next
    End Sub

这样就可以让字段也可以为空了!