问题描述
在C#中,我可以创建一个接口,当我使用的接口编译器知道某个接口要求是由基类实现。这可能是用一个例子更清晰的:
In C# I can create an interface, and when I use the interface the compiler knows that certain interface requirements are fulfilled by the base class. This is probably clearer with an example:
interface FormInterface
{
void Hide();
void Show();
void SetupForm();
}
public partial class Form1 : Form, FormInterface
{
public Form1()
{
InitializeComponent();
}
public void SetupForm()
{
}
}
编译器知道隐藏()和show()的形式实现,上面的代码编译就好了。我无法弄清楚如何在VB.NET做到这一点。当我尝试:
The compiler knows that Hide() and Show() are implemented in Form and the above code compiles just fine. I can't figure out how to do this in VB.NET. When I try:
Public Interface FormInterface
Sub Hide()
Sub Show()
Sub SetupForm()
End Interface
Public Class Form1
Inherits System.Windows.Forms.Form
Implements FormInterface
Public Sub SetupForm() Implements FormInterface.SetupForm
End Sub
End Class
但编译器抱怨说Form1中必须实现'子隐藏()'接口'FormInterface。我是不是真的有添加以下?
But the Compiler complains that Form1 must implement 'Sub Hide()' for interface 'FormInterface'. Do I actually have to add the following?
Public Sub Hide1() Implements FormInterface.Hide
Hide()
End Sub
在我所有的形式,或者是一个更好的路线创建一个抽象基类,有SetupForm()(你怎么在VB.NET做)?
On all my forms, or is a better route creating an abstract base class that has SetupForm() (and how do you do that in VB.NET)?
推荐答案
没有, System.Windows.Forms.Form中
不具有FormInterface实现的,所以不知道它们是否匹配。 VB.NET不做隐式接口的实现,只是明确。
No, System.Windows.Forms.Form
doesn't have the FormInterface implemented, so VB.NET doesn't know they match. VB.NET doesn't do implicit interface implementation, just explicit.
是的,你应该创建一个基类和实现上的接口。我会,不过,他们的名字略有不同。也许 DoShow
和 DoHide
。
Yes, you should create a base class and implement your interface on that. I would, however, name them slightly different. Perhaps DoShow
and DoHide
.
事情是这样的:
Public Class BaseForm
Inherits System.Windows.Forms.Form
Implements FormInterface
Public Sub SetupForm() Implements FormInterface.SetupForm
End Sub
Public Sub DoShow() Implements FormInterface.DoSHow
Me.Show()
End Sub
Public Sub DoHide() Implements FormInterface.DoHide
Me.Hide()
End Sub
End Class
你还能偶然做这样的:
Public Class BaseForm
Inherits System.Windows.Forms.Form
Implements FormInterface
Public Sub SetupForm() Implements FormInterface.SetupForm
End Sub
Public Sub Show() Implements FormInterface.SHow
Me.Show()
End Sub
Public Sub Hide() Implements FormInterface.Hide
Me.Hide()
End Sub
End Class
和会和好如初。
唐'T让基类为MustInherit,因为窗体设计器会不喜欢这样。
Don't make the baseclass MustInherit, because the forms designer won't like that.
这篇关于我怎样才能创建VB.NET与隐含实现一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!