接口

Posted on 2019-11-30 22:41  冰糖Luck1996  阅读(114)  评论(0编辑  收藏  举报

一,接口:2019-11-30

        接口名称通常以I开头

        接口中不能有任何实现的代码

        接口不能有构造函数,字段,运算符重载

        接口成员不用声明为Public

        接口具有强制性,实现一个接口,就必须把接口的所有方法都实现

接口的定义

 public interface IFather
    {
        void IMethod1();
        string IMethod2();
    }

接口的实现

    public class Son : IFather
    {
        public void IMethod1()
        {
            Console.WriteLine("第一个接口方法");
        }

        public string IMethod2()
        {
            throw new NotImplementedException();
        }
        public void SonMethod()
        {
            Console.WriteLine("子类本身的方法");
        }
    }

 

 

        static void Main(string[] args)
        {
            IFather father = new Son();
            father.IMethod1();
            Console.Read();
        }

 

多态

接口作为方法参数

    class Program
    {
        static void Main(string[] args)
        {
            Imethod1(new Son());
            Console.Read();
        }
        public static void Imethod1(IFather father)
        {
            father.IMethod1();      
        }
    }

 

接口作为返回类型

    class Program
    {
        static void Main(string[] args)
        {
            IFather father = Imethod1();
            father.IMethod1();
            Console.Read();
        }
        public static IFather Imethod1()
        {
            return new Son();     
        }
    }