我正在寻找使用只读属性作为 list(of T)
Public ReadOnly Property oList As List(Of String)
Get
Return ...
End Get
当我通常使用 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
或者,使用自动初始化的只读属性(在 Visual Studio 2015 中支持,即 VB14 及更高版本):
Public ReadOnly Property List As List(Of String) = New List(Of String)
现在消费者可以在您的列表中添加和删除:
myObject.List.Add(...)
myObject.List.Remove(...)
但他们不能替换整个列表:
myObject.List = someOtherList ' compile error
myObject.List = Nothing ' compile error
这有几个优点:
List
永远不会是Nothing
的不变性始终得到保证。您类的消费者不能做一些违反直觉的事情,例如“连接”两个对象的列表:
myObject1.List = myObject2.List ' Both objects reference the same list now
作为旁注,我建议在这种情况下公开一个接口(interface)(IList
)而不是具体类:
Public ReadOnly Property List As IList(Of String) = New List(Of String)
这为您提供了上述所有功能。此外,您稍后可以将列表的具体类型更改为例如 MyFancyListWithAdditionalMethods
,而不会违反约定,即,无需重新编译库的使用者。
关于vb.net 类只读属性作为列表(T),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36985104/