2

我创建了以下自定义类来处理特定字符串(“YYY-MM-DD”)作为动态今天值的表示。有几个 ou Widening、Narrowing 和 ToString 函数可以帮助程序员进行代码内转换。

我的问题是当我反序列化时,使用 XmlSerializer,一个使用 MyDateTime 的类。我虽然 XmlSerializer 会使用Narrowing Operator CType(rightSide As String) As MyDateTime, 作为一种对象初始化程序,但在我记得它使用反射之前。

如果我希望 MyDateTime 的 xml 反序列化类属性被初始化,我该怎么办Narrowing Operator CType(rightSide As String) As MyDateTime

Public Class MyDateTime

Const cstUniversalTodayValue As String = "YYYY-MM-DD"

Dim _internalStringRepresentation As String
Dim _internaValue As MyDateTime

Public ReadOnly Property DynamicToday As Boolean
    Get
        Return _internalStringRepresentation = cstUniversalTodayValue
    End Get
End Property

Public Shared Widening Operator CType(rightSide As MyDateTime) As MyDateTime

    Return rightSide._internaValue
End Operator
Public Shared Widening Operator CType(rightSide As MyDateTime) As String

    Return rightSide._internalStringRepresentation
End Operator

Public Shared Narrowing Operator CType(rightSide As MyDateTime) As MyDateTime

    Return New MyDateTime With {._internalStringRepresentation = rightSide.ToString("yyyy-MM-dd"), ._internaValue = rightSide}
End Operator
Public Shared Narrowing Operator CType(rightSide As String) As MyDateTime

    Dim instance = New MyDateTime With {._internalStringRepresentation = rightSide}
    If instance.DynamicToday Then

        instance._internaValue = DateTime.Today
    Else

        instance._internaValue = Convert.ToDateTime(rightSide)
    End If

    Return instance
End Operator

Public Overrides Function ToString() As String
    Return Me
End Function
Public Overloads Function ToString(format As String) As String

    Return _internaValue.ToString(format)
End Function
End Class
4

1 回答 1

0

XmlSerializer 不使用类型转换。只需使用sgen工具为您的类型生成序列化程序程序集,并通过反射器浏览生成的代码以了解其工作原理。

XmlSerializer 实例化执行其构造函数的类并稍后填充其可序列化属性。

要确保您的类的实例被正确序列化,请实现ISerializable接口。您还可以通过实现IXmlSerializable接口来更好地控制 XML 序列化过程。

于 2013-06-19T17:56:32.737 回答