VB.NET语法,用于使用Custom Comparer实例化继承的SortedDictionary

问题描述 投票:1回答:1

这是我的出发点:带有自定义Comparer的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.net visual-studio-2017 icomparer sorteddictionary
1个回答
1
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.