【问题标题】:Error that I must implement a function in a class even though function is defined [duplicate]即使定义了函数,我也必须在类中实现函数的错误[重复]
【发布时间】:2015-07-31 11:31:02
【问题描述】:

我收到错误: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

我错过了什么?

【问题讨论】:

  • 接口方法实现需要Implements关键字。就让IDE帮你跌入成功的坑。删除Function,将光标放在Implements yadayada 行后按回车键。
  • 哇!我以前从未见过这种情况!我只是将其标记为重复,然后我意识到您是几年前提出重复问题的人。好笑……
  • @StevenDoggart:哈哈! :S 有些人永远学不会? :) 不能再删除这个帖子了....

标签: vb.net class interface interface-implementation


【解决方案1】:

与 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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2011-12-22
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      相关资源
      最近更新 更多