开发者

Best Way in VB.Net to Use Generics for My.Settings Persistance?

开发者 https://www.devze.com 2023-01-28 02:45 出处:网络
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 declara

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:

  1. Uses My.Settings for persistance
  2. Reduces code behind bloat from Getters and Setters
  3. Reduces coding errors
  4. Bindable
  5. Implements INotifiyPropertChanged

Disadvantages

  1. Need to append ".Value" to properties.
  2. Need to specify My.Settings property name as string constant.
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消