C#接口理解

接口 关键字 interface

namespace MyInterface
{
    interface IFatherInterface
    {
        void Shout();
    }
}

这边写一个接口

注意:接口中只包含成员的签名,接口没有构造函数,所以不能直接使用new对接口进行实例化。接口中只能包含方法、属性、事件和索引的组合。接口一旦被实现,实现必须实现接口中的所有的成员,除非实现类本身是抽象类

class Dog : IFatherInterface
    {
        public void Shout()
        {
            Console.WriteLine("这是狗");
        }
    }

这边新建一个class 继承接口 IFatherInterface
接口的定义一般以 “I” 开头 后面跟上标志性能理解的单词 因为接口里面有 Shout 方法 我们继承此接口 必要实现 接口里面 Shout方法

这边再新建两个class

 class MyMethod
    {
        public void WriteClass(IFatherInterface item)
        {
            item.Shout();
            Console.WriteLine("***************");
        }
}

 class Cat : ISonInterface
    {


        public void Shout()
        {
            Console.WriteLine("喵喵喵");
        }
    }

这边我们将接口作为参数传入WriteClass

 class Program
    {
    	  static void Main(string[] args)
        {
            MyMethod p = new MyMethod();
            IFatherInterface iclass;
            iclass = new Dog();
            p.WriteClass(iclass);
			
			iclass = new cat();
			p.WriteClass(iclass );
        }
    }

这边输出结果就是

在这里插入图片描述
如果我们cat类的功能比dog类的多的话 那我们再新建一个接口把class Cat继承于ISonInterface

 interface ISonInterface: IFatherInterface
    {
        void aMethod();
    }
    class Cat : ISonInterface
    {
        public void aMethod()
        {
            Console.WriteLine("挠人");
        }

        public void Shout()
        {
            Console.WriteLine("喵喵喵");
        }
    }

我们这边的接口继承了接口IFatherInterface 所以 要实现IFatherInterface和ISonInterface里面的所有方法

 class Program
    {
        static void Main(string[] args)
        {
            MyMethod p = new MyMethod();
            IFatherInterface iclass;
            ISonInterface yclass;

            iclass = new Dog();
            p.WriteClass(iclass);

            yclass = new Cat();
            p.WriteClass(yclass);
            p.SayClass(yclass);
        }
    }

输出结果在这里插入图片描述

接口作用其实就是起到一个规范的作用 举个例子
刚刚的dog类只有叫的功能 而猫类还有挠人的功能 这个时候 你叫小A去实现DOG类
叫小B去实现CAt类 这个时候 他们实现的方法什么的名字都是一样 以后维护也方便维护。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值