Can you improve upon this generic?
I'm trying to reduce code bloat, reduce errors and simplify codebehind by use of generics. In this case I'm applying generic开发者_StackOverflow中文版s to declaration of persistable properties. Persistance is implemented by My.Settings. Here's the code so far.
' must be defined in same project as My.Settings!
Public Class MySettingsProperty(Of T)
Implements System.ComponentModel.INotifyPropertyChanged
Private m_Name As String
Sub New(ByVal Name As String)
m_Name = Name
End Sub
Sub New(ByVal Name As String, ByVal InitialValue As T)
m_Name = Name
Value = InitialValue
End Sub
Public Property Value As T
Get
Return CType(My.Settings(m_Name), T)
End Get
Set(ByVal value As T)
My.Settings(m_Name) = value
RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("Value"))
End Set
End Property
Private Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
Usage:
Public Property Host As New MySettingsProperty(Of String)("Host")
Host.Value = "127.0.0.1"
Debug.WriteLine(Host.Value)
Advantages:
- Uses My.Settings for persistance
- Reduces code behind bloat from Getters and Setters
- Reduces coding errors
- Bindable
- Implements INotifiyPropertChanged
Disadvantages
- Need to append ".Value" to properties.
- Need to specify My.Settings property name as string constant.
- Class must reside in same project as My.Settings declarations.
I just ported this from c#
to vb
so hopefully it's suitable:
Module SettingsHelper
Public Function GetSetting(Of TSetting)(ByVal selector As Func(Of My.MySettings, TSetting)) As TSetting
Return selector(My.Settings)
End Function
Public Sub SetSetting(ByVal action As Action(Of My.MySettings))
action(My.Settings)
End Sub
End Module
And usage:
Debug.WriteLine(SettingsHelper.GetSetting(Function(s) s.Setting1))
SettingsHelper.SetSetting(Sub(s) s.Setting1 = "new value")
Hope this helps.
精彩评论