【问题标题】:Cannot implicitly convert type for interface无法隐式转换接口的类型
【发布时间】: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#


【解决方案1】:

您创建一个新的MoveableOject,将其转换为ILeft,然后尝试将您从转换中获得的ILeft 分配给一个MoveableObject 引用。编译器不同意,正如预期的那样

Ileft iLeftReference = getILeft();
MoveableOject mObj = iLeftReference; // same error

【讨论】:

    【解决方案2】:

    您观察到的错误与ILeft 的显式实现无关。实际上那是因为assignment compatibility。 我们只能将更多派生对象分配给更少派生对象,反之亦然。

    你不能这样做:

    MoveableOject moWithErrorObject = (ILeft) new MoveableOject();
    

    因为MoveableOject 比它的父ILeft 更派生。

    你可以得到一些细节here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多