如何在VB中实现IDictionary(Of TKey,TValue)?

时间:2010-03-02 09:48:27

标签: vb.net generics collections interface

我想创建一个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),但这没有帮助。

1 个答案:

答案 0 :(得分:2)

正确的声明是:

  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将自动插入所有必需的方法和属性。

相关问题