4

你能改进这个通用的吗?

我正在尝试通过使用泛型来减少代码膨胀、减少错误并简化代码隐藏。在这种情况下,我将泛型应用于可持久属性的声明。持久性由 My.Settings 实现。这是到目前为止的代码。

' 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

用法:

Public Property Host As New MySettingsProperty(Of  String)("Host")
Host.Value = "127.0.0.1"
Debug.WriteLine(Host.Value)

优点:

  1. 使用 My.Settings 进行持久化
  2. 减少来自 Getters 和 Setters 的臃肿代码
  3. 减少编码错误
  4. 可绑定
  5. 实现 INotifyPropertChanged

缺点

  1. 需要将“.Value”附加到属性。
  2. 需要将 My.Settings 属性名称指定为字符串常量。
  3. 类必须与 My.Settings 声明位于同一项目中。
4

1 回答 1

0

我只是把它从移植c#vb所以希望它是合适的:

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

和用法:

Debug.WriteLine(SettingsHelper.GetSetting(Function(s) s.Setting1))

SettingsHelper.SetSetting(Sub(s) s.Setting1 = "new value")

希望这可以帮助。

于 2011-06-19T03:20:47.727 回答