繁体   English   中英

将属性的类型传递给泛型函数

[英]Passing the type of the property to generic function

我正在阅读一个文本文件,转换行标题对象或项目对象中每行的数据。 我对nullable有问题

以下代码中的“ p”来自

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

下面的代码引发错误:

从'System.DateTime'到'System.Nullable`1 [[System.DateTime,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]的无效转换

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

类中的相应属性

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

环顾四周后,发现下面的函数,我从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

我已经尝试过使用type1和type2进行操作,但是却收到未定义的错误消息。

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

如何将我的属性类型传递给上述函数?

您可以使用C#给出解决方案。 不需要是VB.Net

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM