代码之家  ›  专栏  ›  技术社区  ›  uriDium

如何在VB中实现IDictionary(Tkey,Tvalue)?

  •  0
  • uriDium  · 技术社区  · 15 年前

    我想创建IDictionary(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
    

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

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

    该类未实现接口“System.Collections.Generic.ICollection(of T)”。我不知道该怎么处理这个错误。我甚至不太明白。我做交易是想把(t)改成(t值),但那没用。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Hans Passant    15 年前

    正确的声明是:

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