VB.NET语法,用于使用自定义比较器实例化继承的SortedDictionary

时间:2018-09-11 20:09:44

标签: vb.net visual-studio-2017 icomparer 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

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

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)向编译器说明我的意图是什么?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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