那么,实现接口显式地有什么好处呢?
只是为了让使用该类的人不必在智能提示中查看所有这些方法/属性吗?
在明确定义接口的情况下,所有方法都会自动变为私有方法,您无法将访问修饰符 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