C#中的 隐式与显式接口实现

在C#中,正常情况下使用接口的实现使用的是 隐式接口实现

public interface IParent1
{
    void Medthod();
}

public class Child : IParent1
{
    public void Medthod()
    {
        Console.WriteLine("Child 中的实现方法");
    }
}

C# 编译器假定Child中的Medthod的方法是对接口IParent1中Medthod方法的时候。C#编译器之所以这样做出假定,是因为Medthod方法的可访问性是public,而且接口方法的签名和新引入的方法完全一致。也就是说两个方法具有相同的参数和返回类型。如果新的Test方法被标记为virtual,C#编译器仍会认为该方法匹配与接口方法。

C# 会将新方法的实现和接口的实现认为是同一种实现。

static void Main(string[] args)
{
    Child child = new Child();
    child.Medthod();
    IParent1 test1 = child;
    test1.Medthod();

    Console.ReadKey();
}

因为方法的实现和接口的实现被认定为同一种方法,那输出的结果就是一样的。

将定义那个接口名称作为方法名的前缀,例如上面的IParent1.Medthod()。创建的就是一个 显式接口方法实现(Explicit Interface Method Implementation ,EIMI)。注意,在C#中定义一个显式接口方法时,不允许指定可访问性(public或者private等)。否则编译器汇报错误,例如下图。

显式接口的实现类默认是private,防止其他类直接使用实例中的方法,只能通过接口来调用。EIMI的方法也不能标记为virtual,所以他不能重写。这是因为EIMI方法并非真的是类型对象模型的一部分,它是将一个接口(一组行为或者方法)连接到一个类型上,同时避免公开行为/方法的一种方式。所以使用类对象也不能点出改方法。

接口类在调用方法时,使用的也是显式实现中的实现。 

static void Main(string[] args)
{
    Child child = new Child();
    child.Medthod();
    IParent1 test1 = child;
    test1.Medthod();

    Console.ReadKey();
}


public interface IParent1
{
    void Medthod();
}

public class Child : IParent1
{
    public void Medthod()
    {
        Console.WriteLine("Child 中的实现方法");
    }

    void IParent1.Medthod()
    {
        Console.WriteLine("显式实现的IParent的方法");
    }
}

 输出的结果:

参考博客:https://blog.csdn.net/u010533180/article/details/72954192

猜你喜欢

转载自www.cnblogs.com/gp112/p/10744757.html