VB.net 接口无法编译,为什么?
问题:我正在尝试在这里转换它: http://support.microsoft.com/kb/828736 到 VB.net
我让它在 C# 中工作,它应该在 VB.net 中工作没有问题,唯一的问题是托管类无法编译,我收到此错误:
错误类“ManagedClass”必须为 ICalculator 接口实现“Function Add(Number1 As Integer, Number2 As Integer) As Integer”
为什么?我看到声明了一个函数,并实现了一个函数,并且具有相同的参数...出了什么问题?
Imports System
Imports System.Collections.Generic
Imports System.Text
Namespace TestLibrary2
' Interface declaration.
Public Interface ICalculator
Function Add(ByVal Number1 As Integer, ByVal Number2 As Integer) As Integer
End Interface
' Interface implementation.
Public Class ManagedClass
Implements ICalculator
Public Function Add(ByVal Number1 As Integer, ByVal Number2 As Integer) As Integer
Return Number1 + Number2
End Function
End Class
End Namespace
Question: I'm trying out to convert this here:
http://support.microsoft.com/kb/828736
to VB.net
I got it to work in C#, and it should work without problems in VB.net, the only problem is the managed class won't compile, i get this error:
Error Class "ManagedClass" has to implement "Function Add(Number1 As Integer, Number2 As Integer) As Integer" for the ICalculator-Interface
Why? I see one function declared, and one implemented, and that with the same arguments... What's wrong ?
Imports System
Imports System.Collections.Generic
Imports System.Text
Namespace TestLibrary2
' Interface declaration.
Public Interface ICalculator
Function Add(ByVal Number1 As Integer, ByVal Number2 As Integer) As Integer
End Interface
' Interface implementation.
Public Class ManagedClass
Implements ICalculator
Public Function Add(ByVal Number1 As Integer, ByVal Number2 As Integer) As Integer
Return Number1 + Number2
End Function
End Class
End Namespace
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 VB.Net 中,您必须明确接口实现 - 这比 C# 具有更大的灵活性(因为您可以根据自己的喜好命名函数),但工作量要多一些。
正如 MA Hanin 和我自己都提到的 - 它可以让你选择名字,但我们都没有提到为什么你可能想要这样做。一个例子是,如果您正在实现两个定义相同方法名称的接口。并且您希望将这两个方法公开为类中的公共方法。在 C# 中,您必须创建至少一个“包装”函数来调用另一个函数来实现这一目标。
In VB.Net, you have to be explicit about your interface implementation - this allows more flexibility than C# (because you can name your functions whatever you like), but is a little more work.
As both M.A. Hanin and myself have mentioned - it lets you pick the names, but neither of us mentioned yet why you might want to do this. One example would be if you're implementing two interfaces that both define the same method name. And you want to expose both of these methods as public methods on your class. In C#, you'd have to create at least one "wrapper" function that calls another to achieve this.
您只需告诉它具有完全相同名称和定义的函数的类确实是您想要处理接口函数的类。
you just need to tell it that the class that has a function with exactly the same name and definition is really what you want to handle the interface function.