C#基础:接口(三)

    本文将简要介绍接口的显式实现。

    先看下面的代码:

interface IInterfaceA
{
    int GetValue(int x);
}

interface IInterfaceB
{
    int GetValue(int x);
}

class Concrete : IInterfaceA, IInterfaceB
{
    
}

    在上面的代码中,Concrete类同时实现了IInterfaceA和IInterfaceB。由于IInterfaceA和IInterfaceB有着同样的函数签名,此时如果Concrete类以实例方法来实现GetValue函数,势必会导致无论是用IInterfaceA的实例还是IInterfaceB的实例来调用GetValue函数,都会产生同样的结果。比如下面的代码会输出两个20:

interface IInterfaceA
{
    int GetValue(int x);
}

interface IInterfaceB
{
    int GetValue(int x);
}

class Concrete : IInterfaceA, IInterfaceB
{
    public int GetValue(int x)
    {
        return x + 10;
    }
}

class Program
{
    static void Main(string[] args)
    {
        IInterfaceA ia = new Concrete();
        Console.WriteLine(ia.GetValue(10));

        IInterfaceB ib = new Concrete();
        Console.WriteLine(ib.GetValue(10));
    }
}

    此时,两个接口公用了同一个函数实现。然而在更多的情况下,虽然两个接口有着相同签名的函数,但我们仍希望针对不同接口有着各自不同的函数实现。接口的显式实现就是解决这样的问题。请看下面的代码:

interface IInterfaceA
{
    int GetValue(int x);
}

interface IInterfaceB
{
    int GetValue(int x);
}

class Concrete : IInterfaceA, IInterfaceB
{
    int IInterfaceA.GetValue(int x)
    {
        return x + 10;
    }

    int IInterfaceB.GetValue(int x)
    {
        return x + 20;
    }
}

class Program
{
    static void Main(string[] args)
    {
        IInterfaceA ia = new Concrete();
        Console.WriteLine(ia.GetValue(10));

        IInterfaceB ib = new Concrete();
        Console.WriteLine(ib.GetValue(10));
    }
}

    上面的代码输出了20和30,达到了我们的要求。需要注意的是,如果直接使用Concrete类的实例,是无法调用到GetValue函数的,因为类里面没有名称为GetValue的实例函数(Instance Method)。

    从实现上看,接口的显式实现具有下面的格式:

  • 函数以<接口名>.<函数在接口中的名称>命名,例如上面的IInterfaceA.GetValue和IInterfaceB.GetValue
  • 接口的显式实现函数不能带访问修饰符(比如public,protected等)

    显式接口还有一些妙用,比如,针对未提供泛型版本的接口,为其提供类型安全机制,并能有效避免繁杂的装箱、拆箱操作。有关这方面的详细描述读者可以参考《CLR via C#》一书或其它文献资源。时间关系,我就不在这详述了。

原文地址:https://www.cnblogs.com/daxnet/p/1686979.html