C# 接口显示实现和隐式实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wodownload2/article/details/80752001

c#中类可以实现多个接口,那么如果不同的接口有相同的方法名的话,此时需要显示实现。举例:
第1个接口:

interface InterfaceA
    {
        void Say();
    }

第2个接口:

interface InterfaceB
    {
        void Say();
    }

实现类:

class Person:InterfaceA, InterfaceB
    {
        void InterfaceA.Say()
        {
            Console.WriteLine("helloA");
        }

        void InterfaceB.Say()
        {
            Console.WriteLine("helloB");
        }
    }

访问形式:

class Program
{
        static void Main(string[] args)
        {
            InterfaceA p = new Person();
            p.Say();

            InterfaceB p2 = new Person();
            p2.Say();
        }
}

显示实现只能通过对应的接口访问对应的接口内的方法。用实现类去访问时访问不到的。
其实很好理解,就是显示实现需要指定到具体的哪个接口的哪个方法,防止函数名冲突,调用模糊。

猜你喜欢

转载自blog.csdn.net/wodownload2/article/details/80752001