Mec*_*eer 2 vb.net properties class list readonly
我正在寻找一个使用 a 的例子 read-only property as list(of T)
Public ReadOnly Property oList As List(Of String)
Get
Return ...
End Get
Run Code Online (Sandbox Code Playgroud)
当我通常使用 list(of T) 时,我总是New
在变量类型前面使用构造函数Public Property oList as New list(of T)
但是当我现在这样做时,我从 Visual Studio 收到一条错误消息。那么这是如何工作的呢?
我以前从未使用过只读属性..
这是一个简单的例子:
Private myList As New List(Of String)
Public ReadOnly Property List As List(Of String)
Get
Return myList
End Get
End Property
Run Code Online (Sandbox Code Playgroud)
或者,使用自动初始化的只读属性(在 Visual Studio 2015 中支持,即 VB14 及更高版本):
Public ReadOnly Property List As List(Of String) = New List(Of String)
Run Code Online (Sandbox Code Playgroud)
现在消费者可以在您的列表中添加和删除:
myObject.List.Add(...)
myObject.List.Remove(...)
Run Code Online (Sandbox Code Playgroud)
但它们不能替换整个列表:
myObject.List = someOtherList ' compile error
myObject.List = Nothing ' compile error
Run Code Online (Sandbox Code Playgroud)
这有几个优点:
List
永远不会的不变量Nothing
总是得到保证。你的类的使用者不能做违反直觉的事情,比如“连接”两个对象的列表:
myObject1.List = myObject2.List ' Both objects reference the same list now
Run Code Online (Sandbox Code Playgroud)作为旁注,我建议在这种情况下公开接口( IList
) 而不是具体类:
Public ReadOnly Property List As IList(Of String) = New List(Of String)
Run Code Online (Sandbox Code Playgroud)
这为您提供了上述所有功能。此外,您可以稍后更改列表的具体类型,例如,在MyFancyListWithAdditionalMethods
不违反合同的情况下,即无需重新编译库的使用者。
归档时间: |
|
查看次数: |
2394 次 |
最近记录: |