.NET之一——接口的显式与隐式实现

当我们定义接口的成员的时候不需要写访问控制符,因为它是默认public的,也只能是public.当一个类要实现这个接口的时候,自然要公开其成员。
interface Interface1
{   
    string GetUserName(string name);
}
class Class1:Interface1
{   
    public string GetUserName(string name)
    {
       return name;
    }   
}

一直以来我都这么做,而且也认为理所当然的。前几天,复习.net的知识时,无意中发现.net中接口还可以显示的实现,我们所常用的只是隐式实现而已。

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    interface Interface1
    {
        int Method1();
        int Method2();
    }


    interface Interface2
    {
        int Method1();
        int Method2();
    }
}

 

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class TestClass : Interface1, Interface2
    {

        public void TestMethod()
        {
            Interface1 inf1 = (Interface1)this;
            Console.WriteLine("return value is :" + inf1.Method1());
            Interface2 inf2 = (Interface2)this;
            Console.WriteLine("return value is :" + inf2.Method2());
            Console.WriteLine("return value is :" + this.Method1());//调用的是隐式实现的方法
            Console.WriteLine("return value is :" + this.Method2());//调用的是隐式实现的方法
        }

        int Interface2.Method1()
        {
            return 1;
        }
        int Interface2.Method2()
        {
            return 2;
        }
        int Interface1.Method1()
        {
            return 3;
        }
        int Interface1.Method2()
        {
            return 4;
        }

        public int Method1()
        {
            return 5;
        }
        public int Method2()
        {
            return 6;
        }
    }


}

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            new TestClass().TestMethod();
        }      
    }
}

输出为:

return value is :3

return value is :2

return value is :5

return value is :6

 

 

显示实现接口说明:

  1、不能在方法调用、属性访问以及索引指示器访问中通过全权名访问显式接口成员执行体。事实上,显式接口成员执行体只能通过接口的实例,也就是仅仅引用接口的成员名称来访问;

  2、显式接口成员执行体不能使用任何访问限制符,也不能加上abstract, virtual, override或static 修饰符,即使是public也不可以;

  3、显式接口成员执行体和其他成员有着不同的访问方式。因为不能在方法调用、属性访问以及索引指示器访问中通过全权名访问,显式接口成员执行体在某种意义上是私有的。但它们又可以通过接口的实例访问,也具有一定的公有性质;

  4、只有类在定义时,把接口名写在了基类列表中,而且类中定义的全权名、类型和返回类型都与显式接口成员执行体完全一致时,显式接口成员执行体才是有效的;

  5、一个类中既显示又隐式的实现接口,这时显式实现方法只能通过接口的引用来直接访问,隐式实现方法只可以通过类的实例来直接访问;

        6、一个类如果实现恶劣多个接口,并且这多个被实现的接口含有相同签名的接口声明,那么如果其中有一个被显式实现,那么其它接口中同签名的方法也必须被显式实现。

  为什么要显示实现接口呢,有如下好处:

  1、因为显式接口成员执行体不能通过类的实例进行访问,这就可以从公有接口中把接口的实现部分单独分离开。如果一个类只在内部使用该接口,而类的使用者不会直接使用到该接口,这种显式接口成员执行体就可以起到作用。

  2、显式接口成员执行体避免了接口成员之间因为同名而发生混淆。如果一个类希望对名称和返回类型相同的接口成员采用不同的实现方式,这就必须要使用到显式接口成员执行体。如果没有显式接口成员执行体,那么对于名称和返回类型不同的接口成员,类也无法进行实现。


 

 

发布了53 篇原创文章 · 获赞 2 · 访问量 18万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章