项目设置似乎在序列化和保存基本类型之外的值方面做得不好。您可以做的是使用用户范围的字符串值设置来存储序列化字典。
对于我的示例,我创建了一个名为SerializedKeyPercentDictionary
Typestring
和 Scope的设置User
。我使用 JSON 进行序列化,因为它创建的字符串比大多数其他序列化的长度更短。为此,您需要添加对 System.Runtime.Serializations 的引用。有了这个设置和那个引用,你就可以创建一个全局帮助类来提供一个强类型的字典来管理你的键到百分比的映射:
Public Class KeyPercentHelper
Private Shared _keyPercentDictionary As Dictionary(Of Integer, Decimal)
Private Shared _initLock As Object = New Object()
Public Shared ReadOnly Property KeyPercentDictionary As Dictionary(Of Integer, Decimal)
Get
If (_keyPercentDictionary Is Nothing) Then
InitializeDictionary()
End If
Return _keyPercentDictionary
End Get
End Property
Shared Sub New()
AddHandler My.Settings.SettingsLoaded, AddressOf HandleSettingsLoad
AddHandler My.Settings.SettingsSaving, AddressOf HandleSettingsSaving
End Sub
Private Shared Sub InitializeDictionary()
' Load dictionary from User Setting.
SyncLock _initLock
If (_keyPercentDictionary Is Nothing) Then
If (String.IsNullOrEmpty(My.Settings.SerializedKeyPercentDictionary)) Then
_keyPercentDictionary = New Dictionary(Of Integer, Decimal)()
Else
Dim ser As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(Dictionary(Of Integer, Decimal)))
Using memStream As New System.IO.MemoryStream()
Using writer As New System.IO.StreamWriter(memStream)
writer.Write(My.Settings.SerializedKeyPercentDictionary)
writer.Flush()
memStream.Position = 0
_keyPercentDictionary = CType(ser.ReadObject(memStream), Dictionary(Of Integer, Decimal))
End Using
End Using
End If
End If
End SyncLock
End Sub
Private Shared Sub HandleSettingsLoad(ByVal sender As Object, ByVal e As EventArgs)
If (_keyPercentDictionary Is Nothing) Then
InitializeDictionary()
End If
End Sub
Private Shared Sub HandleSettingsSaving(ByVal sender As Object, ByVal e As EventArgs)
' Ensure User Setting value is updated before save.
Dim ser As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(Dictionary(Of Integer, Decimal)))
Using memStream As New System.IO.MemoryStream()
ser.WriteObject(memStream, _keyPercentDictionary)
memStream.Position = 0
Using reader As New System.IO.StreamReader(memStream)
My.Settings.SerializedKeyPercentDictionary = reader.ReadToEnd()
End Using
End Using
End Sub
End Class