接口学习

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

namespace 学习
{

    class 接口
    {
    }
    //c#是单继承的,一个类只能从一个父类继承,但接口是多实现的,一个类可以用来实现多个接口

    public interface Walkable
    {
        void Walk();
    }
    public interface Flayble //定义一个接口
    {
        void Fly();//创建这个接口的方法,但不能添加public 等修饰符,也不能实现这个接口
       // int _age;//会报错,接口中不能有字段

        int Age { get; set; }//但是可以实现属性,因为属性的本质是方法,也可以实现索引,索引的本质也是方法
    }

    public class Birds : Flayble,Walkable //说的时候说“实现了某个接口”,不能说成继承了一个接口,看似
                                 //和类的继承差不多
    {
        #region Flayble 成员

        public void Fly()
        {
            Console.WriteLine("我是可以飞的接口");
        }

        public int Age
        {

            get;
            set;
        }
       
        #endregion
        public void Walk()
        {
            Console.WriteLine("我也可以走");
        }

调用过程

            学习.Birds birds1 = new Birds();
            birds1.Fly();
            birds1.Walk();
            //接口的多态性
            学习.Flayble bird2 = birds1;//把一个变量赋值给他高一级的变量,但是只能用这个变量来应用
                                        //对应的接口,就像birds2就没有Walk()方法。
            bird2.Fly();
            Console.ReadKey();

灰常适合初学者学习!

原文地址:https://www.cnblogs.com/xinyebs/p/2454712.html