C#学习笔记(8)-接口

作用

继承具有单根性,也就是一个子类只能有一个父类。若这个子类向调用另一个子类中的方法,可以考虑使用接口。

关键字

  • 语法
    [public ] interface I…able
    {
    成员;
    }

-接口就是一个规范,一种能力
-接口中的成员不允许添加访问修饰符,默认就是public
-接口成员不能有方法体
-接口不能包含字段
-接口能包含自动属性
-索引器
-接口中只能包含方法

代码示例:

public class Person
    {
        public void CHLSS()
        {
            Console.WriteLine("我是人类,我可以吃喝拉撒睡");
        }
    }

    public class NBAPlayer : Person
    {
        public void KouLan()
        {
            Console.WriteLine("我可以扣篮");
        }
    }

    public class Student:Person,KouLanable
    {
        public void KouLan()
        {
            Console.WritLine("我也可以扣篮");
        }
    }

    public interface KouLanable
    {
        void KouLan();
        string Name()//自动属性
        {
            get;
            set;
        }
    }

接口的特点

-接口不能被实例化 //抽象类不可以实例化,静态类不可以实例化
-接口可以相互继承接口,继承的接口包含父接口的所有方法。实现接口的子类,必须实现接口的全部成员
-一个类可以同时继承一个类并实现多个接口,如果一个子类同时继承了父类A,并继承了接口IA,那么语法上A必须写在IA的前面

显示实现接口

为了避免类的方法与类中的方法重名的问题

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

namespace _14显示实现接口
{
    class Program
    {
        static void Main(string[] args)
        {
            IFlyable fly = new Bird();
            fly.Fly();//调用接口的飞
            Bird b = new Bird();
            b.Fly();//调用类的飞
            Console.ReadKey();
        }
    }

    public class Bird:IFlyable
    {
        public void Fly()
        {
            Console.WriteLine("鸟会废");
        }

        void IFlyable.Fly()//显示调用接口的方法
        {
            Console.WriteLine("我是接口的废");
        }
    }

    public interface IFlyable
    {
        void Fly();
    }
}

猜你喜欢

转载自blog.csdn.net/lonesome_zxq/article/details/80551437