使用Windows窗体实现接口
本文关键字:接口 实现 窗体 Windows 使用 | 更新日期: 2023-09-27 18:27:33
我是使用接口的新手,所以我有一个问题对你们大多数人来说可能很容易。
我目前正在尝试制作一个windows窗体的界面。它看起来有点像
interface myInterface
{
//stuff stuff stuff
}
public partial class myClass : Form, myInterface
{
//More stuff stuff stuff. This is the form
}
当我尝试实现它时,问题就来了。如果我用实现
myInterface blah = new myClass();
blah.ShowDialog();
ShowDialog()函数现在可以使用了。这是有道理的-myInterface是一个接口,而不是一个窗体……但我很好奇我应该如何用windows窗体实现这个接口,或者它是否是一个可行的选项。
有人对我该怎么做有什么建议吗?
谢谢!
实现这一点的一种方法是将ShowDialog添加到myInterface:
interface myInterface
{
DialogResult ShowDialog();
}
现在,您可以在接口上调用该方法,而不必强制转换。
如果你想对它更感兴趣,你可以创建另一个代表任何对话框的界面。。。
interface IDialog
{
DialogResult ShowDialog();
}
然后让你的另一个接口实现IDialog:
interface myInterface : IDialog
{
//stuff stuff stuff
}
这具有潜在的重用更多代码的优势。。。您可以使用接受IDialog类型参数的方法,而不必了解myInterface。如果你为所有对话框实现了一个通用的基本接口,你可以用同样的方式处理:
void DialogHelperMethod(IDialog dialog)
{
dialog.ShowDialog();
}
myInterface foo = new myClass();
DialogHelperMethod(foo);
interface MyInterface
{
void Foo();
}
public partial class MyClass : Form, MyInterface
{
//More stuff stuff stuff. This is the form
}
Form f = new MyClass();
f.ShowDialog(); // Works because MyClass implements Form
f.Foo(); // Works because MyClass implements MyInterface
这似乎是一个关于如何正确公开类成员的问题。
internal - Access to a method/class is restricted to the application
public - Access is not restricted
private - Access is restricted to the current class (methods)
protected - Access is restricted to the current class and its inherited classes
接口的一个示例是在类之间共享通用方法签名
interface IAnimal
{
int FeetCount();
}
public class Dog : IAnimal
{
int FeetCount()
{
}
}
public class Duck : IAnimal
{
int FeetCount()
{
}
}
您只能访问用于保存myClass的类型所公开的项。例如,
Form f = new MyClass();
f.ShowDialog(); // Will work because f is of type Form, which has a ShowDialog method
f.stuff(); // Works because MyClass implements myInterface which exposes stuff()
所有你想要的东西都在那里,但你必须以不同的方式引用它们。