为什么要显式实现接口?

124

那么,实现接口显式地有什么好处呢?

只是为了让使用该类的人不必在智能提示中查看所有这些方法/属性吗?

11个回答

0

在明确定义接口的情况下,所有方法都会自动变为私有方法,您无法将访问修饰符 public 分配给它们。例如:

interface Iphone{

   void Money();

}

interface Ipen{

   void Price();
}


class Demo : Iphone, Ipen{

  void Iphone.Money(){    //it is private you can't give public               

      Console.WriteLine("You have no money");
  }

  void Ipen.Price(){    //it is private you can't give public

      Console.WriteLine("You have to paid 3$");
  }

}


// So you have to cast to call the method


    class Program
    {
        static void Main(string[] args)
        {
            Demo d = new Demo();

            Iphone i1 = (Iphone)d;

            i1.Money();

            ((Ipen)i1).Price();

            Console.ReadKey();
        }
    }

  // You can't call methods by direct class object

1
“所有方法都自动成为私有方法” - 从技术上讲,这并不正确,因为如果它们实际上是私有的,那么无论是否进行强制转换,它们都将无法被调用。 - samus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接