C# 接口 interface

C# 接口

1.接口就是一个规范、能力
代码:

            [public] interface I..able
            { 成员}

2.接口中的成员不允许添加访问修饰符,默认就是public,接口中不允许写具有方法体的函数

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

namespace 接口
{
    internal class Program
    {

        static void Main(string[] args)
        {
            
            IFlyable flyable = new Person();
            flyable.Fly();//人类会飞
            Console.ReadKey();
        }
    }


    public class Person : IFlyable
    {
        public void Fly()
        {
            Console.WriteLine("人类在飞");
        }

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

    }
    public interface IFlyable
    {
        //接口中的成员不允许添加访问修饰符,默认就是public
        //不允许写具有方法体的函数
        //方法、自动属性、索引器
        void Fly();
        //string Test();
    }
    public interface M1
    {
        void Test1();
    }
    public interface M2
    {
        void Test2();
    }
    public interface M3
    {
        void Test3();
    }
    public interface su : M1, M2, M3
    {
    }


  
}

接口特点

    //接口特点:接口是一种规范,只要一个类继承了一个接口,这个类就必须实现这个接口中所有的成员
    //接口不能被实例化,也就是说,接口不能new(不能创建对象) 
    //接口中的成员不允许添加访问修饰符,默认就是public,不能修改
    //接口中的成员不能有任何实现(没有方法体,“光说不做”,只是定义了一组未实现的成员)
    //接口中只能有方法、自动属性、索引器、事件、不能有“字段”和构造函数
    //接口与接口之间可以继承,并且可以多继承
    //接口并不能去继承一个类,而类可以实现接口(接口只能继承与接口,而类既可以继承接口,也可以继承类)
    //实现接口的子类必须实现该接口的全部成员
    //一个类可以同时继承一个类并实现多个接口,如果一个子类同时继承了父类A,并实现了接口IA,那么语法上A必须写在IA的前面
    //class MyClass:A,IA{},因为类是单继承的
    //显示实现接口的目的,解决方法的重名问题

显示实现接口

显示实现接口就是为了解决方法的重名问题

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

namespace ConsoleApp2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //显示实现接口就是为了解决方法的重名问题
            IFlyable flyable = new Bird();
            flyable.fly();//我是接口的飞
            Bird bird = new Bird();
            bird.fly();//鸟会飞
            Console.ReadKey();

        }
    }

    public class Bird : IFlyable
    {
        public void fly()
        {
            Console.WriteLine("鸟会飞");
        }
        void IFlyable.fly()
        {
            Console.WriteLine("我是接口的飞");
        }
    }

    public interface IFlyable
    { void fly(); }
}

你可能感兴趣的:(c#基础知识,c#,开发语言,ui)