博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

接口为什么有实现和显示实现两种

Posted on 2008-11-17 10:47  strong.xu  阅读(204)  评论(0编辑  收藏  举报

一、继承接口的类如果没有与接口具有同样放回类型和签名的方法,这时可以默认实现接口也可以显式实现接口,否则,就只能显式实现接口。

注意:显式实现接口的方法必须通过接口对象访问,而不能通过类对象进行访问

例如:

 

interface InterfaceTest
    {
        void Priter(string content);
        void Save(string content);
    }

    class StudentInfo : InterfaceTest
    {
        public void Priter(string content)//(1)
        {
            Console.WriteLine(content);
        }

        public void Save(string content)//(2)
        {
            Console.WriteLine(content);
        }

        #region InterfaceTest Members

        void InterfaceTest.Priter(string content)//(3)
        {
            Console.WriteLine(content);
        }

        void InterfaceTest.Save(string content)//(4)
        {
            Console.WriteLine(content);
        }

        #endregion
    }

 

static void Main(string[] args)
        {
            StudentInfo student = new StudentInfo();
            student.Priter("Object priter student information");
            student.Save("Object save student information");
            InterfaceTest testInterface = student;
            testInterface.Priter("Interface priter student information");
            testInterface.Save("Interface save student information");
            Console.ReadKey();
        }

上例子对代码进行跟踪的时候可以发现,student对象访问的是Priter,Save方法,而接口对象testInterface访问的是InterfaceTest.PriterInterfaceTest.Save方法。

如果对上例子中的(1),(2)方法注释掉,那么就会报错误 1 'ConsoleApplication1.StudentInfo' does not contain a definition for 'Priter' 

但是如果对(3),(4)方法注释掉(也就是非显式实现接口),那么不会报错

当我们需要一个方法返回一个接口,而想实现某种模式的时候,我们最好利用显式实现接口,如果仅仅是满足接口的约束功能,那么就没有必要显式实现,这还要根据实际情况来决定