类既扩展了抽象类又实现了接口
如果我有一个既扩展抽象类又实现接口的类,例如:
class Example : AbstractExample, ExampleInterface
{
// class content here
}
如何初始化此类,以便可以从接口和抽象类访问方法?
当我这样做时:
AbstractExample example = new Example();
我无法从界面访问方法。
What if I have a class that both extends an abstract class and implements an interface, for example:
class Example : AbstractExample, ExampleInterface
{
// class content here
}
How can I initialize this class so I can access methods from both the interface and the abstract class?
When I do:
AbstractExample example = new Example();
I cannot access methods from the interface.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要
或获取对 Example
示例示例=新示例();
You need to
Example example = new Example();
最后一个例子将把你与接口或抽象类的实体实例联系起来,我认为这不是你的目标。坏消息是你在这里不是使用动态类型语言,所以你只能坚持引用实体“Example”对象如先前指定的或铸造/取消铸造即:
您的其他选择是让 AbstractExample 和 IExampleInterface 实现一个通用接口,这样您就可以拥有 ie
现在您可以使用 ICommonInterface 并具有抽象类和您的 IExample 接口的实现。
如果这些答案都不可接受,您可能需要查看一些在 .NET 框架下运行的 DLR 语言,即 IronPython。
The last example will tie you to a solid instance of either the interface or abstract class which I presume is not your goal.The bad news is you're NOT in a dynamically typed language here, so your stuck with either having a reference to a solid "Example" objects as previously sprcified or casting/uncasting i.e:
Your other alternitives are to have both AbstractExample and IExampleInterface implement a common interface so you would have i.e.
Now you could work with ICommonInterface and have the functionality of both the abstract class and the implementation of your IExample interface.
If none of these answers are acceptable, you may want to look at some of the DLR languages that run under the .NET framework i.e. IronPython.
如果您只知道抽象类,则表明您通过
Type
实例了解实际类型。 因此,您可以使用泛型:If you only know the abstract class, it suggests that you know the actual type via an instance of
Type
. Therefore, you could use generics:使用:
在更多信息后更新:
如果您确定它实现了ExampleInterface,您可以使用
您也可以通过检查接口来确保它确实实现了它
我不相信泛型可以帮助您,因为它们是解决了编译时间问题,如果您只有对 AbstractClass 的引用,编译器会抱怨。
编辑:或多或少是欧文所说的。 :)
Use:
Updated after more information:
If you are sure it implements ExampleInterface, you can use
You can also make sure it really implements it by checking the interface with
I don't believe Generics help you as those are resolved compile time and if you only have a reference to the AbstractClass the compiler will complain.
Edit: So more or less what Owen said. :)
我认为这个例子会对你有所帮助:
I think this example will help you: