【问题标题】:How do I implement IDictionary(Of TKey, TValue) in VB?如何在 VB 中实现 IDictionary(Of TKey, TValue)?
【发布时间】:2011-01-22 15:51:56
【问题描述】:

我想创建一个 IDictionary(Of TKey, TValue) 接口的实现来提供一些包装功能。

Public Class ExtendedDictionary(Of TKey, TValue)
    Implements IDictionary(Of TKey, TValue)

    Private _Dictionary As Dictionary(Of TKey, TValue)

    Public Sub Add(ByVal key As TKey, ByVal value As T) Implements IDictionary(Of TKey, T).Add
    'Impl Here'
    End Sub

End Class

当我这样做时,它会抱怨我没有实施的方法。当我选择实现 ICollection 的方法时,会添加 ICollection,但随后会出现一大堆错误。他们中的一些人抱怨具有相同签名的方法。例如:

Public ReadOnly Property IsReadOnly() As Boolean Implements ICollection(Of KeyValuePair(Of TKey, T)).IsReadOnly
        Get
            Return IsReadOnly
        End Get
    End Property

所以我认为这个错误很容易修复。只需更改方法的名称,因为我们告诉它它实现了哪个方法,因此名称应该无关紧要。所以我把它改成 Lick CollectionIsReadOnly。更难的问题如下:

    ReadOnly Public Property Count() As Integer Implements ICollection(Of T).Count
        Get
            Return Count
        End Get
    End Property

错误是这个类没有实现接口'System.Collections.Generic.ICollection(Of T)。我不确定如何处理此错误。我什至不明白。我进行交易以将 (Of T) 更改为 (Of TValue) 但这没有帮助。

【问题讨论】:

    标签: vb.net generics collections interface


    【解决方案1】:

    正确的声明是:

      Public ReadOnly Property Count() As Integer Implements System.Collections.Generic.ICollection(Of System.Collections.Generic.KeyValuePair(Of TKey, TValue)).Count
        Get
          ' implementation here...
        End Get
      End Property
    

    IntelliSense 可以帮助您正确地获得这些声明,但它非常不稳定。从写这个开始:

    Public Class ExtendedDictionary(Of TKey, TValue)
    End Class
    

    光标向上并插入这一行:

    Implements IDictionary(Of TKey, TValue)
    

    当您在最后的 ) 后按 Enter 时,IDE 将自动插入所有必需的方法和属性。

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多