为什么?重新声明东西来实现接口?!在VB.NET中
我在 VB.NET v2 中工作,
我有一个接口 IMyInterface,该接口实现了一个方法 MyMethod。
我有一个对象MyObjectBase。该对象包含一个(相同的)方法MyMethod。
1) 如果现在我MyObject Inherits MyObjectBase Implements IMyInterface
需要重新定义吗?(阴影,覆盖)MyMethod
在 MyObject
类中?
2) 如果我有一个 MyEvent
event 代替 MyMethod
方法,现在该怎么办?
谢谢。
I work in VB.NET v2
I have an interface IMyInterface and this interface implements a method MyMethod.
I have an object MyObjectBase. This object contains a(the same) method MyMethod.
1) If now I do MyObject Inherits MyObjectBase Implements IMyInterface
need I to redefine? (shadow, override) MyMethod
in the MyObject
class?
2) What now if instead the MyMethod
method I have an MyEvent
event?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 VB.NET 中,您需要手动将接口契约与实现关联起来。看一下下面的示例:
然后看一下下面的代码及其输出:
这样做的优点是实现接口不会限制您按照自己的意愿命名函数。缺点是您必须使用
Implements
关键字显式地将类方法与接口声明关联起来。关于解释就这么多。现在让我解决您的问题:由于您无法使
Button
实现 IVisibleChanged,因此您可以执行以下操作:MyBase
是引用超类的 VB.NET 关键字。同样,对于MyMethod
,您可以这样做这可能看起来像是不必要的额外工作,但在某种程度上,它是有意义的:
Button.VisibleChanged
和IVisibleChanged .VisibleChanged
可能是具有两种完全不同语义的事件,只是碰巧具有相同的名称(毕竟Button
没有实现IVisibleChanged)。通过您的代码,您可以显式地在这两者之间创建连接。
In VB.NET, you need to manually associate your interface contract with your implementations. Have a look at the following example:
Then have a look at the following code and its output:
This has the advantage that implementing an interface does not restrict you in naming your function as you want to. The disadvantage is that you have to explicitly associate your class methods with your interface declarations using the
Implements
keyword.So much about an explanation. Now let me get to your problem: Since you cannot make
Button
implement IVisibleChanged, you can do something like that:MyBase
is a VB.NET keyword referring to the superclass. Likewise, in the case ofMyMethod
, you can doThis might seem like unnecessary extra work, but in a way, it makes sense:
Button.VisibleChanged
andIVisibleChanged.VisibleChanged
might be events with two completely different semantics, who just happen to have the same name (after allButton
does not implementIVisibleChanged
). With your code, you explicitly create a connection between those two.这是因为你实现了你的子类,所以你必须重新定义它。我相信,如果您只是从基本情况继承(无论如何都已实现),那么如果您不需要它,则不必这样做。
It's because you implement your child class that you have to redefine it. I believe if you just inherit from the base case, which is implemented anyway, you won't have to if you don't need it.