我有一个关于泛型类的序列化的问题。
因为我想为我的所有配置(被序列化为 XML)使用一个通用类,所以我编写了以下类:
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Imports System.Reflection
Imports System.Reflection.Assembly
<Serializable()> _
Public Class GenericConfig(Of T)
Public Sub WriteToFile(ByVal FileName As String)
ConfigVersion = ProgrammVersion.ToString
Dim XmlFile As FileStream = New FileStream(FileName, FileMode.Create)
Dim serialize As XmlSerializer = New XmlSerializer(GetType(GenericConfig(Of T)), New Type() {GetType(GenericConfig(Of T))})
serialize.Serialize(XmlFile, Me)
XmlFile.Close()
End Sub
Public Shared Function ReadFromFile(ByVal FileName As String) As GenericConfig(Of T)
Dim XmlFile As FileStream = New FileStream(FileName, FileMode.Open)
Dim serialize As XmlSerializer = New XmlSerializer(GetType(GenericConfig(Of T)))
ReadFromFile = serialize.Deserialize(XmlFile)
XmlFile.Close()
Return ReadFromFile
End Function
Public Shared ReadOnly Property ConfigFileName() As String
Get
Return GetExecutingAssembly.Location.Substring(0, GetExecutingAssembly.Location.Length - 4) & ".Config.xml"
End Get
End Property
End Class
Public Class ToolConfig
Inherits GenericConfig(Of ToolConfig)
Public Property Key1 As String = "Value 1"
End Class
我遇到的问题是我无法序列化它,因为出现以下错误
serialize.Serialize(XmlFile, Me)
{“类型 GenericConfigClass.ToolConfig 不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。”}
如果您在派生类上使用 XMLSerializer,我已经搜索并发现了很多与该错误相关的文章。我在这里不这样做。我在通用类上使用它。
除了在这里创建像这个家伙这样的 XML 帮助器类之外,还有其他方法吗:http: //www.codeproject.com/Articles/35925/Generic-XML-Serialization-Methods
谢谢,
沃尔夫冈
更新:
这就是我所说的(简短的例子)
Imports System.IO
Public Class frmMain
Dim Config As ToolConfig
Private Sub btnConfigInit_Click(sender As Object, e As EventArgs) Handles btnConfigInit.Click
'----------------- read config file -----------------
If File.Exists(ToolConfig.ConfigFileName) Then
Config = ToolConfig.ReadFromFile(ToolConfig.ConfigFileName)
Else
Config = New ToolConfig
End If
Config.WriteToFile(ToolConfig.ConfigFileName)
MsgBox(Config.Key1)
End Sub
End Class