使用VB.Net中的TypeConverter将Object转换为另一种类型的Object

时间:2016-10-23 17:37:38

标签: vb.net typeconverter

我正在尽力了解TypeConverters的使用以及如何使用它们。

Imports System.ComponentModel
Imports System.Globalization

<TypeConverter(GetType(OrderTypeConverter))>
Public Class OrderType1

Public Sub New()

Public Sub New(Order As OrderType2)
    OrderNumber = Order.OrderNo
    'Etc Etc
End Sub

Public Property OrderNumber As String
Public Property OrderDescription As String

End Class

Public Class OrderType2

Public Property OrderNo As String
Public Property Description As String

End Class

Public Class OrderTypeConverter
Inherits TypeConverter

Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
    If destinationType = GetType(OrderType2) Then
        Return True
    End If

    Return MyBase.CanConvertTo(context, destinationType)
End Function

Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object

    If destinationType = GetType(OrderType2) Then

        Dim OldOrder As OrderType1 = DirectCast(value, OrderType1)

        Dim NewOrder As New OrderType2
        NewOrder.Description = OldOrder.OrderDescription
        NewOrder.OrderNo = OldOrder.OrderNumber

        Return NewOrder
    End If

    Return MyBase.ConvertTo(context, culture, value, destinationType)
End Function

End Class

如果上述内容正确无误,我不确定如何实现转换。

我知道另一种方法是将OrderType2订单传递给OrderType1订单的新方法,然后通过所有属性等等,但必须有更好的方法

0 个答案:

没有答案