你能改进这个通用的吗?
我正在尝试通过使用泛型来减少代码膨胀、减少错误并简化代码隐藏。在这种情况下,我将泛型应用于可持久属性的声明。持久性由 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)
优点:
- 使用 My.Settings 进行持久化
- 减少来自 Getters 和 Setters 的臃肿代码
- 减少编码错误
- 可绑定
- 实现 INotifyPropertChanged
缺点
- 需要将“.Value”附加到属性。
- 需要将 My.Settings 属性名称指定为字符串常量。
- 类必须与 My.Settings 声明位于同一项目中。