有没有办法动态创建my.settings变量?我希望根据数据库中的值生成my.settings变量,因此my.settings变量的数量需要随时间变化。
如果我的数据库中有以下值,
0
2
6
13
77生成的my.settings变量的名称为
My.Settings.M0
My.Settings.M2
My.Settings.M6
My.Settings.M13
My.Settings.M77所以我想在应用程序第一次运行时创建这些变量。从数据库中获取数字后的问题。如何使用代码创建这些变量?
另外,有没有一种方法可以用代码删除它们,因为当数据库的值发生变化而值不存在时,我需要删除它的变量?
此外,如果这不是一个好的方式,我想要一些建议。
发布于 2012-08-04 02:34:38
项目设置似乎不能很好地序列化和保存超出基本类型的值。您可以做的是使用用户范围的字符串值设置来存储序列化字典。
对于我的示例,我创建了一个名为SerializedKeyPercentDictionary的设置,类型为string,作用域为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 Classhttps://stackoverflow.com/questions/11799780
复制相似问题