学习C#接口

学习C#接口(interface)

以下均为在菜鸟教程中学习的笔记


接口定义了所有类继承接口时应遵循的语法合同。接口定义了语法合同“是什么”,派生类定义了语法合同“怎么做”

接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。

成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。

接口使得实现接口的类或结构在形式上保持一致。

抽象类在某种程度上与接口类似,但是,它们大多只是用在当只有少数方法由基类声明由派生类实现时。


定义接口:

接口使用interface关键字声明。它与类的声明类似。接口声明默认时public的。

以下代码定义了接口IMyInterface。通常接口命令以I字母开头,这个接口只有一个方法MethodToImplement(),没有参数和返回值,当然我们可以按照需求设置参数和返回值。

运用的实例:

interface IMyInterface
    {
        //接口成员
        void MethodToImplement();
    }
    class Program : IMyInterface
    {
        //定义接口里成员方法的成员
        public void MethodToImplement()
        {
            Console.WriteLine("1");
        }
    }
    class test
    {
        static void Main()
        {
            Program p = new Program();
            p.MethodToImplement();
        }
    }

结果:

1

接口继承

以下实例定义了两个接口IMyInterface和IParentInterface。

如果一个接口继承了其他接口,那么实现类或数据结构就需要实现所有接口的成员

实例:

interface IParentInterface
    {
        void ParentInterfaceMethod();
    }
    interface IMyInterface:IParentInterface
    {
        //接口成员
        void MethodToImplement();
    }

    class Program : IMyInterface
    {
        //定义接口里成员方法的成员
        public void MethodToImplement()
        {
            Console.WriteLine("1");
        }
        public void ParentInterfaceMethod()
        {
            Console.WriteLine("2");
        }
    }
    class test
    {
        static void Main()
        {
            Program p = new Program();
            p.MethodToImplement();
            p.ParentInterfaceMethod();
        }
    }

结果:

1
2

注意:

接口不能用public abstract等修饰。

接口可以定义属性。如 string color{get;set}

实现接口时,必须与接口的格式一致且实现接口里的所有方法

猜你喜欢

转载自www.cnblogs.com/wei1349/p/12905014.html