簡體   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