vb.net class 只读 属性 作为列表(属于 T)

vb.net class read-only property as list(of T)

我正在寻找 read-only property as list(of T)

的用法示例
Public ReadOnly Property oList As List(Of String)
Get
    Return ...
End Get

当我通常使用 list(of T) 时,我总是在我的变量类型 Public Property oList as New list(of T)

前面使用 New 构造函数

但是当我现在这样做时,我从 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 的不变量始终得到保证。
  • 您 class 的消费者不能做违反直觉的事情,例如 "connecting" 两个对象的列表:

    myObject1.List = myObject2.List   ' Both objects reference the same list now
    

作为旁注,我建议在这种情况下公开一个 接口 (IList) 而不是具体的 class:

Public ReadOnly Property List As IList(Of String) = New List(Of String)

这为您提供了上述所有功能。此外,您可以稍后将列表的具体类型更改为 MyFancyListWithAdditionalMethods,而不会违反约定,即无需重新编译库的使用者。