即使定义了函数,我也必须在类中实现一个函数

时间:2015-05-19 14:49:34

标签: vb.net class interface interface-implementation

我收到错误:Class 'QueryParameterComparer' must implement 'Function Compare(x As QueryParameter, y As QueryParameter) As Integer' for interface 'System.Collections.Generic.IComparer(Of QueryParameter)'.

在这个类定义上:

    Protected Class QueryParameterComparer
        Implements IComparer(Of QueryParameter)

        Public Function Compare(x As QueryParameter, y As QueryParameter) As Integer
            If x.Name = y.Name Then
                Return String.Compare(x.Value, y.Value)
            Else
                Return String.Compare(x.Name, y.Name)
            End If
        End Function

    End Class

我也尝试过完全写出来:

    Protected Class QueryParameterComparer
        Implements System.Collections.Generic.IComparer(Of QueryParameter)

        Public Function Compare(x As QueryParameter, y As QueryParameter) As Integer
            If x.Name = y.Name Then
                Return String.Compare(x.Value, y.Value)
            Else
                Return String.Compare(x.Name, y.Name)
            End If
        End Function

    End Class

我错过了什么?

2 个答案:

答案 0 :(得分:9)

与c#不同,其中方法的名称必须与接口中的名称相匹配,在VB.NET中,所有接口实现必须始终在每个成员上使用Implements关键字明确声明:

Protected Class QueryParameterComparer
    Implements IComparer(Of QueryParameter)

    Public Function Compare(x As QueryParameter, y As QueryParameter) As Integer Implements IComparer(Of QueryParameter).Compare
        ' ...
    End Function
End Class

答案 1 :(得分:3)

VB.Net要求您指定哪些方法是接口的实现方法。

Public Function Compare(x As QueryParameter, y As QueryParameter) As Integer Implements System.Collections.Generic.IComparer(Of QueryParameter).Compare

这很奇怪,但它确实允许您为实现指定不同的函数名称。这使得直接访问您的类可以为该函数指定一个名称,但通过该接口的引用将具有接口方法名称。您可以做的其他事情是将方法指定为Private,以便您只能通过接口引用访问该方法。