C#接口和类继承

Mds*_*dsm -2 c# inheritance interface object

我在我的对象中使用接口方法时遇到问题.我是一个快速的例子,没有所有的补充.

public class Item{}
public interface IFruit
{
      void MethodExample();
}

public class Apple : Item, IFruit
{
    public void IFruit.MethodExample(){}
}

// put this in a run method somewhere
var example_item = new Apple();

//Here comes the problem.
example_item.MethodExample();
// this will return an error saying that it cant find the method.
Run Code Online (Sandbox Code Playgroud)

无论如何要做到这一点?我知道它实现了i_fruit.并有方法.但我无法访问它?

Dar*_*dan 5

首先,请阅读c#命名约定.其次,你已经i_fruit明确地实现了接口,你应该example_item转换为i_fruit或者更常见的方式是i_fruit隐式实现接口.请阅读:https: //blogs.msdn.microsoft.com/mhop/2006/12/13/implicit-and-explicit-interface-implementations/

隐式实现示例:

public class Apple : Item, IFruit
{
   public MethodExample(){}
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您想坚持显式实现,那么您应该将代码更改为:

IFruit example_item;
example_item = new Apple();
Run Code Online (Sandbox Code Playgroud)