【发布时间】:2015-11-08 19:56:09
【问题描述】:
stackoverflow 中有一些类似线程的重复,但这并不完全相同,所以我再次在这里发布。让我们考虑以下示例。
public interface ILeft
{
void Move();
}
public class MoveableOject : ILeft
{
//without public we get an error
public void Move()
{
Console.WriteLine("Left moving");
}
}
class Program
{
static void Main(string[] args)
{
MoveableOject mo = new MoveableOject();
mo.Move();
Console.ReadKey();
}
}
一切都很好。现在让我们考虑 ILeft 的显式实现。为什么注释行会给出上述错误信息?
class MoveableOject : ILeft
{
void ILeft.Move()
{
Console.WriteLine("Left moving");
}
}
class Program
{
static void Main(string[] args)
{
MoveableOject mo = new MoveableOject();
// MoveableOject moWithErrorObject = (ILeft) new MoveableOject(); <--
((ILeft)mo).Move();
((ILeft)new MoveableOject()).Move();
Console.ReadKey();
}
}
编辑:2015 年 11 月 8 日,错误语句中的 MoveableOject 应该是 ILeft 可以理解的,我错误地把它放在那里。为什么我贴出来原因我无法解释,让我们使用对象并通过以下方式传递给方法。
public static void ExpectDerivedPassedDerived(MoveableOject passedObject)
{
passedObject.Move();
}
现在,如果我从 Main 调用该方法,它应该可以工作吗?但这不是因为我有明确的实现,但如果我使用 public 关键字实现,那就没问题了,我正在寻找对此的解释。
ExpectDerivedPassedDerived(mo); //mo is MoveableOject type
【问题讨论】:
-
这与显式接口无关。
MoveableObject继承自ILeft,而不是相反。 -
显式实现允许您的方法仅在转换为接口本身时才可访问。 ILeft 在这种情况下。
-
有人可以对编辑后的代码发表评论吗?这是我提出这个问题的初衷。谢谢。
-
我评论有点晚了,也许您已经知道了,但是您在 2015 年 11 月 8 日的评论中提到的问题是
MoveableOject类明确地实现了接口ILeft。在这种情况下,我们必须通过显式接口((ILeft)passedObject).Move()访问对象passedObject。好文章是例如here.
标签: c#