在 C# 中的抽象类上使用接口
我正在从 C++ 学习 C#,但遇到了困难。
我有一个抽象类 AbstractWidget、一个接口 IDoesCoolThings 和一个从 AbstractWidget 派生的名为 RealWidget 的类:
public interface IDoesCoolThings
{
void DoCool();
}
public abstract class AbstractWidget : IDoesCoolThings
{
void IDoesCoolThings.DoCool()
{
Console.Write("I did something cool.");
}
}
public class RealWidget : AbstractWidget
{
}
当我实例化一个 RealWidget 对象并在其上调用 DoCool() 时,编译器会给出一个错误:
“RealWidget”不包含 “DoCool”的定义
我可以将 RealWidget 对象转换为 IDoesCoolThings,然后调用就会起作用,但这似乎没有必要,而且我也失去了多态性(即使我定义了 RealWidget.DoCool(),AbstractWidget.DoCool() 也将始终被调用)。
我想解决方案很简单,但我尝试了多种方法,但我一生都无法解决这个问题。
I'm learning C# coming from C++ and have run into a wall.
I have an abstract class AbstractWidget, an interface IDoesCoolThings, and a class which derives from AbstractWidget called RealWidget:
public interface IDoesCoolThings
{
void DoCool();
}
public abstract class AbstractWidget : IDoesCoolThings
{
void IDoesCoolThings.DoCool()
{
Console.Write("I did something cool.");
}
}
public class RealWidget : AbstractWidget
{
}
When I instantiate a RealWidget object and call DoCool() on it, the compiler gives me an error saying
'RealWidget' does not contain a
definition for 'DoCool'
I can cast RealWidget object to an IDoesCoolThings and then the call will work, but that seems unnecessary and I also lose polymorphism (AbstractWidget.DoCool() will always be called even if i define RealWidget.DoCool()).
I imagine the solution is simple, but I've tried a variety of things and for the life of me can't figure this one out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您遇到此问题是因为您使用了 < em>显式接口实现 (EII)。 当显式实现成员时,不能通过类实例来访问它,只能通过接口的实例来访问。 在您的示例中,这就是为什么您无法调用
DoCool()
,除非您将实例强制转换为IDoesCoolThings
。解决方案是将
DoCool()
公开并删除显式接口实现:通常,您在两种情况下使用 EII:
You're running into the issue because you used explicit interface implementation (EII). When a member is explicitly implemented, it can't be accessed through a class instance -- only through an instance of the interface. In your example, that's why you can't call
DoCool()
unless you cast your instance toIDoesCoolThings
.The solution is to make
DoCool()
public and remove the explicit interface implementation:In general, you use EII in two cases:
如果您选择隐式实现接口,则实现接口的方式是显式实现 void IDoesCoolThings.DoCool()。
然后它就会起作用。
阅读此内容:
C# 接口。 隐式实现与显式实现
The way you implement the interface is explicit implement void IDoesCoolThings.DoCool(), if you choose implicit implement interface.
Then it will work.
Read this :
C# Interfaces. Implicit implementation versus Explicit implementation
将您的声明更改为:
Change your declaration to:
你应该这样做:
用法:
You should do it this way:
Usage: