接口

实现接口的任何类都必须实现其所有的方法

接口不能直接实例化

接口可以包含方法和属性声明,不能包含字段

接口中所有属性和方法默认为public

一个子类可以继承一个父类的同时,实现多个接口

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 接口
 7 {
 8     //食物接口
 9     public interface Food
10     {
11         //在接口中定义属性,属性不能实现
12         float Price { get; }
13 
14         //在接口中定义方法
15         //1.不能添加访问修饰符,默认都是public 
16         //接口中的方法不能有方法体  在接口中只能有方法定义,不能有方法实现
17         void eat();
18     }
19     //定义一个父类
20     public class A
21     {
22  
23     }
24     public interface B
25     { 
26 
27     }
28 
29     //定义一个苹果的子类,
30     //Apple 继承于A类,并实现了Food接口
31     //一旦某个类实现了接口,就必须实现接口中定义的全部成员    
32     public class Apple : A, Food
33     {
34         
35         void Food.eat()   //public void eat()
36         {
37             Console.WriteLine("吃下苹果后,HP+10");
38         }
39 
40         public float Price
41         {
42             get
43             {
44                 return 1.4f;
45             }
46         }
47     }
48 
49     public class Banana : Food
50     {
51 
52         public float Price
53         {
54             get 
55             {
56                 return 5.6f;
57             }
58         }
59 
60         public void eat()
61         {
62             Console.WriteLine("吃下香蕉后,HP-10");
63         }
64     }
65 
66     class Program
67     {
68         static void Main(string[] args)
69         {
70             Food f = new Apple();
71             f.eat();
72             Console.WriteLine(f.Price);
73 
74             Banana bana = new Banana();
75             bana.eat();
76 
77             Console.ReadKey();
78         }
79     }
80 }
原文地址:https://www.cnblogs.com/jc-1997/p/6080989.html