接口学习

来源:互联网 发布:科比巅峰数据 编辑:程序博客网 时间:2024/06/06 06:58

接口

1、接口不包括方法的实现,实现接口的任何类/任何非抽象类型都必须实现其所有的成员方法;

2、接口中只包含成员的签名,接口没有构造函数,故接口不能直接实例化(接口可以实例化);

3、接口可以包含方法和属性声明,方法、属性、事件、索引器可以作为接口成员;

4、接口中所有属性和方法默认为public,故C#接口的成员不能有public、protected、internal、private等修饰符;

5、一个子类只能继承一个父类,可以实现多个接口,即C#是单继承,接口解决C#里面类可以同时继承多个基类的问题;

6、接口可以作为方法的返回值。


using System;namespace lesson01{public class A{}//接口需要添加interface关键字  public  interface  Food {    //1.接口中定义属性,属性不能实现float Price {get;}    //2.接口中定义方法,方法不能实现,不能添加访问修饰符,默认都是publicvoid Eat ();  }        //Apple 继承A类,并且实现了Food接口      //3.实现接口的任何类都必须实现其所有的成员方法      public class Apple : A,Food  { public float Price {          get{           return 1.4f;    }             }  public void Eat (){                        //实现接口中的方法          Console.WriteLine ("吃下苹果后,HP + 10");          }     }  class MainClass {   public static void Main ( string[] args ) {    Apple a = new Apple () ;   a.Eat () ;            Console.WriteLine (a.Price) ;  Food b = new Apple () ;           //使用接口实现的多态 b.Eat ();          Console.WriteLine (b.Price) ;     //Food f = new Food ;4.不能够直接实例化接口          }   }}