Passing the type of the property to generic function

时间:2018-11-09 17:37:25

标签: c# vb.net system.reflection

I am reading a text file, translate the data where each line either goes in header object or items object. I am having an issue with nullables

'p' in below code is coming from

Dim properties As PropertyInfo() = GetType(UploadMain).GetProperties()

The code below throws the error:

Invalid cast from 'System.DateTime' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

p.SetValue(header, Convert.ChangeType(dataObject, p.PropertyType))

the corresponding property in the class

private _orderDate As Date?
        Public Property OrderDate As Date?
            Get 
                Return _orderDate
            End Get
            Set(value As Date?)
                _orderDate = value
            End Set
        End Property

After looking around, found the following function, which i translated from C#

Public Class ChangeTypeUtlity

        Public Shared Function ChangeType(Of T)(ByVal value As Object) As T
            Dim conversionType As Type = GetType(T)

            If conversionType.IsGenericType AndAlso conversionType.GetGenericTypeDefinition().Equals(GetType(Nullable)) Then

                If value Is Nothing Then
                    Return Nothing
                Else
                    Dim nullableConverter As NullableConverter = New NullableConverter(conversionType)
                    conversionType = nullableConverter.UnderlyingType
                End If
            End If

            Return CType(Convert.ChangeType(value, conversionType), T)
        End Function

    End Class

I have tried it with both type1 and type2 but getting error that it is not defined.

Dim type1 as Type = p.[GetType]()
Dim type2 As Type = p.PropertyType
p.SetValue(header, ChangeTypeUtlity.ChangeType(Of type2)(dataObject))

How can i pass my property type to the above function?

You can give the solution in C#. It doesn't need to be VB.Net

1 个答案:

答案 0 :(得分:1)

您的问题出在ChangeType上,您甚至需要它吗?如果这样做,请检测该属性是否为Nullable,如果可以,则可以使用GetUnderlyingType

Convert.ChangeType(dataObject, Nullable.GetUnderlyingType(p.PropertyType))