首页 > 解决方案 > 使用自定义比较器实例化继承的 SortedDictionary 的 VB.NET 语法

问题描述

这是我的起点:带有自定义比较器的 SortedDictionary:

Dim dict As SortedDictionary(Of Long, Object) = New SortedDictionary(Of Long, Object)(New CustomComparer())

为了实现额外的功能,我需要扩展我的字典,所以我现在有了这个:

Public Class CustomDict
    Inherits SortedDictionary(Of Long, Object)
End Class

Dim dict As CustomDict = New CustomDict

到目前为止一切都很好。现在我只需要添加我的自定义比较器:

Dim dict As CustomDict = New CustomDict()(New CustomComparer())

但是编译器认为我正在尝试创建一个二维数组。

结果是,如果我使用扩展 SortedDictionary 的类,则在使用自定义比较器时会出现编译器错误,因为它认为我正在尝试创建一个数组。我期望的是它将代码识别为实例化继承 SortedDictionary 的类,并让它使用自定义比较器。

总而言之,这编译:

Dim dict As SortedDictionary(Of Long, Object) = New SortedDictionary(Of Long, Object)(New CustomComparer())

虽然这会产生与二维数组相关的编译器错误:

Public Class CustomDict
    Inherits SortedDictionary(Of Long, Object)
End Class

Dim dict As CustomDict = New CustomDict()(New CustomComparer())

我的语法错了吗?或者是否有 Visual Studio 设置(2017 Professional)向编译器阐明我的意图是什么?任何援助将不胜感激。

标签: vb.netvisual-studio-2017icomparersorteddictionary

解决方案


当继承一个类时,除了它的构造函数之外几乎所有的东西都被继承了。因此,您必须自己创建构造函数并使其调用基类的构造函数:

Public Class CustomDict
    Inherits SortedDictionary(Of Long, Object)

    'Default constructor.
    Public Sub New()
        MyBase.New() 'Call base constructor.
    End Sub

    Public Sub New(ByVal Comparer As IComparer(Of Long))
        MyBase.New(Comparer) 'Call base constructor.
    End Sub
End Class

或者,如果您总是想为您的自定义字典使用相同的比较器,您可以跳过第二个构造函数,而是让默认构造函数指定要使用的比较器:

Public Sub New()
    MyBase.New(New CustomComparer())
End Sub

推荐阅读