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

标签 vb.net list class properties readonly

我正在寻找使用只读属性作为 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/

相关文章:

python - 为什么这段代码的Death类中没有 'self'?

python - 属性错误 : 'str' object has no attribute 'transID'

c# - C# 中是否有类似 VB.NET 的运算符?

vb.net - 将通用列表转换为字符串数组

r - 通过 R 中的循环命名列表项

java - 将对象添加到通用列表

java - 为什么类 Car 会存储对象 car 和 car2 的正确信息,但类 Owner 不会存储对象 Owner2 的信息?

.net - FOR XML 要求的无效 XML 标识符

c# - 日期时间在转换时出错

python - 如何将整数列表加入一个整数python