简体   繁体   English

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

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

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 我对nullable有问题

'p' in below code is coming from 以下代码中的“ p”来自

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]]' 从'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))

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# 环顾四周后,发现下面的函数,我从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. 我已经尝试过使用type1和type2进行操作,但是却收到未定义的错误消息。

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#. 您可以使用C#给出解决方案。 It doesn't need to be VB.Net 不需要是VB.Net

Your problem is with ChangeType, do you even need it? 您的问题出在ChangeType上,您甚至需要它吗? If you do, detect if the property is Nullable, if it is you can then use GetUnderlyingType 如果这样做,请检测该属性是否为Nullable,如果可以,则可以使用GetUnderlyingType

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

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

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