【问题标题】:vb.net class read-only property as list(of T)vb.net 类只读属性作为列表(T)
【发布时间】:2016-08-27 09:00:38
【问题描述】:

我正在寻找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 收到一条错误消息。 那么这是如何工作的呢?

我以前从未使用过只读属性..

【问题讨论】:

  • 在类构造函数中初始化私有支持字段 var。或者,您可以在返回之前检查它是否为空。

标签: vb.net list class properties readonly


【解决方案1】:

这是一个简单的例子:

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
    

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    相关资源
    最近更新 更多