接口、抽象類、抽象方法、虛方法總結
阿新 • • 發佈:2017-05-20
blog 方法 實例 類名 class 訪問修飾符 檢查 spa code
一、接口
1、定義
1.1、訪問修飾符 interface 接口名{成員可以為屬性、方法、事件、索引器}
1.2、示例代碼
public delegate void DelInfo(int Id); public interface IInformation { //屬性 int Id { get; set; } int[] ArrayInt { get; set; } //方法 void IGetInfo(); //事件 event DelInfo IDelInfo;//索引器 long this[int index] { get; set; } }
2、特點
2.1、接口內的成員都不能被實現;
2.2、接口可以被多繼承;
2.3、接口不能被實例化;
2.4、接口中不能包含常量、字段(域)、構造函數、析構函數、靜態成員;
二、抽象類、抽象方法
1、定義
1.1、訪問修飾符 abstract class 抽象類名
1.2、示例代碼
public delegate void DelInformation(int id); public abstract class BaseInformation {//字段 private int _id; //屬性 public int Id { get { return _id; } set { _id = value; } } //事件 event DelInformation EventDelInformation; //普通方法 public void GetInformation(int id) { Console.WriteLine(id); if (this.EventDelInformation != null) this.EventDelInformation(1); } //虛方法 public virtual int GetId() { return Id; } //抽象方法 public abstract int GetInfo(); //索引器 //可容納100個整數的整數集 private long[] arr = new long[100]; //聲明索引器 public long this[int index] { get { //檢查索引範圍 if (index < 0 || index >= 100) { return 0; } else { return arr[index]; } } set { if (!(index < 0 || index >= 100)) { arr[index] = value; } } } }
2、特點
2.1、和接口一樣不能被實例化;
2.2、如果包含抽象方法,類必須為抽象類;
2.3、具體派生類必須覆蓋基類的抽象方法;
2.4、抽象類中的虛方法可以被覆寫也可以不覆寫;
2.5、抽象派生類可以覆蓋基類的抽象方法,也可以不覆蓋;
三、虛方法
1、定義
1.1、在方法前加上virtual;
1.2、示例代碼
public virtual void GetId() { Console.WriteLine(""); }
2、特點
2.1、要有方法體;
2.2、可以在派生類中覆寫,也可以不覆寫;
接口、抽象類、抽象方法、虛方法總結