Windows 10通用应用。 VB
我有下面的类要保存到文件并从文件中读取,保存工作但是当我尝试加载时我得到了错误。
消息=第1行位置错误249.元素' http://schemas.datacontract.org/2004/07/KoW_Universal_v2:MagicItem'包含' http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfKeyValueOfstringMagicItemyoeMIiQz'的数据。数据合同。反序列化器不知道映射到此合同的任何类型。添加对应于' ArrayOfKeyValueOfstringMagicItemyoeMIiQz'到已知类型列表 - 例如,通过使用KnownTypeAttribute属性或将其添加到传递给DataContractSerializer的已知类型列表。 源= System.Private.DataContractSerialization
Imports System.Runtime.Serialization
Imports Windows.Storage
Public Class MagicItem
Property MagicItemName As String
Property MagicItemCost As Integer
Property MagicItemDescripyion As String
Property LimitToHero As Boolean
Property LimitToSpecialRule As String 'key to the special rule
End Class
Public Class clsMagicItems
Private MagicItems As New Dictionary(Of String, MagicItem)
Async Sub SaveMagicItems()
' StorageFile File = Await openPicker.PickSingleFileAsync();
Dim myfile As StorageFile
myfile = Await ApplicationData.Current.LocalFolder.CreateFileAsync("MagicItems.dat", CreationCollisionOption.ReplaceExisting)
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(clsMagicItems))
KnownTypeList.Add(GetType(MagicItem))
Dim r As Streams.IRandomAccessStream
r = Await myfile.OpenAsync(FileAccessMode.ReadWrite)
Using outStream As Streams.IOutputStream = r.GetOutputStreamAt(0)
Dim serializer As New DataContractSerializer(GetType(clsMagicItems), KnownTypeList)
serializer.WriteObject(outStream.AsStreamForWrite(), MagicItems)
Await outStream.FlushAsync()
outStream.Dispose()
r.Dispose()
End Using
End Sub
Async Sub LoadMagicItems()
Try
Dim myfile As Stream
Dim KnownTypeList As New List(Of Type)
KnownTypeList.Add(GetType(clsMagicItems))
KnownTypeList.Add(GetType(MagicItem))
Dim serializer As New DataContractSerializer(GetType(clsMagicItems), KnownTypeList)
myfile = Await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("MagicItems.dat")
'LINE BELOW RAISE ERROR
MagicItems = serializer.ReadObject(myfile)
Catch
'failed to load the file
End Try
End Sub
End Class
答案 0 :(得分:0)
修正了它,应该有以下代码
KnownTypeList.Add(GetType(Dictionary(Of String, MagicItem)))
...
Dim serializer As New DataContractSerializer(GetType(Dictionary(Of String, MagicItem)), KnownTypeList)