1. 程式人生 > >【學習筆記】C# 接口

【學習筆記】C# 接口

apple [] oat 訪問 names 使用 foo pub 修飾

  • 使用interface關鍵字定義接口
  • 接口定義一組成員但不直接實現它們
  • 實現接口
    • 實現接口的任何類都必須實現其所有的成員方法
    • 接口不能直接實例化
    • 接口可以包含方法和屬性聲明,不能包含字段
    • 接口中所有屬性和方法默認為public
    • 一個子類可以繼承一個父類的同時,實現多個接口
  •   
     1 using System;
     2 
     3 namespace InterfaceDemo
     4 {
     5     //食物接口
     6     public interface Food
     7     {
     8         //在接口中定義屬性,屬性也不能實現
     9         float price { set
    ; get; } 10 11 //在接口中,定義方法 12 //1. 不能添加訪問修飾符,默認都是public 13 //2. 在接口中的方法不能實現 14 void Eat(); 15 } 16 public interface B 17 { 18 19 } 20 //蘋果類 21 //Apple繼承於A類,並且實現了Food接口和B接口 22 //3. 一旦某個類實現了接口,就必須實現接口中定義的全部成員 23 public class Apple : Food, B 24 {
    25 public float price 26 { 27 get 28 { 29 return 1.5f; 30 } 31 set 32 { 33 this.price = value; 34 } 35 } 36 //實現了 Food 接口中的 Eat 方法 37 public void Eat() 38 {
    39 Console.WriteLine("吃下蘋果後,hp + 10"); 40 } 41 } 42 43 public class Banana : Food, B 44 { 45 public float price 46 { 47 get 48 { 49 return 3.8f; 50 } 51 set 52 { 53 this.price = value; 54 } 55 } 56 //實現了 Food 接口中的 Eat 方法 57 public void Eat() 58 { 59 Console.WriteLine("吃下香蕉後,hp + 12"); 60 } 61 } 62 class Program 63 { 64 static void Main(string[] args) 65 { 66 Apple a = new Apple(); 67 a.Eat(); 68 69 Console.WriteLine(a.price); 70 71 //多態--使用接口實現的多態 72 Food b = new Apple(); 73 b.Eat(); 74 75 76 Banana ba = new Banana(); 77 ba.Eat(); 78 Console.WriteLine(ba.price); 79 //4. 不能夠直接實例化接口 80 //Food f = new Food(); 81 } 82 } 83 }

【學習筆記】C# 接口