下面我们直接用实例来讲解:
1.首先我们分别定义接口Ishow1、Ishow2、Ishow3。
interface IShow1
{
void Get ();
void Set ();
}
interface IShow2
{
void Get ();
void Set ();
}
interface IShow3
{
void Get ();
void Set ();
}
2.定义一个Class同时调用上述接口。
public class Show : IShow1, IShow2, IShow3
{
public void Set ()
{
Console.WriteLine("Set");
}
public void Get ()
{
Console.WriteLine("Get");
}
void IShow1.Get ()
{
Console.WriteLine("Get 1");
}
void IShow2.Get ()
{
Console.WriteLine("Get 2");
}
void IShow3.Get ()
{
Console.WriteLine("Get 3");
}
}
3.分别调用。
static void Main (string[] args)
{
Show show = new Show(); // 隐士接口
show.Get();
IShow1 show1 = new Show(); // 显式接口
show1.Get();
IShow2 show2 = new Show(); // 显式接口
show2.Get();
IShow3 show3 = new Show(); // 显式接口
show3.Get();
Console.ReadKey();
}
输出结果将会是:
Get
Get 1
Get 2
Get 3
应用场景:
当类实现一个接口时,通常使用隐式接口实现,这样可以方便的访问接口方法和类自身具有的方法和属性。当类实现多个接口时,并且接口中包含相同的方法签名,此时使用显式接口实现。即使没有相同的方法签名,仍推荐使用显式接口,因为可以标识出哪个方法属于哪个接口。
隐式接口实现,类和接口都可访问接口中方法。显式接口实现,只能通过接口访问。