C#語言有很多值得學習的地方,這裡我們主要介紹C# abstract修飾符,包括介紹通常用於強制繼承類必須實現某一成員。等方面。
C# abstract修飾符是什麼意思?
C# abstract修飾符可以用於類、方法、屬性、事件和索引指標(indexer),表示其為抽象成員 abstract 不可以和 static 、virtual 一起使用聲明為 abstract 成員可以不包括實現代碼,但只要類中還有未實現的抽象成員(即抽象類別),那麼它的對象就不能被執行個體化,通常用於強制繼承類必須實現某一成員。
樣本:
- using System;
- using System.Collections.Generic;
- using System.Text;
-
- namespace Example04
- {
- #region 基類,抽象類別
- public abstract class BaseClass
- {
- //抽象屬性,同時具有get和set訪問器表示繼承類必須將該屬性實現為可讀寫
- public abstract String Attribute
- {
- get;
- set;
- }
-
- //抽象方法,傳入一個字串參數無傳回值
- public abstract void Function(String value);
-
- //抽象事件,類型為系統預定義的代理(delegate):EventHandler
- public abstract event EventHandler Event;
-
- //抽象索引指標,只具有get訪問器表示繼承類必須將該索引指標實現為唯讀
- public abstract Char this[int Index]
- {
- get;
- }
- }
- #endregion
-
- #region 繼承類
- public class DeriveClass : BaseClass
- {
- private String attribute;
-
- public override String Attribute
- {
- get
- {
- return attribute;
- }
- set
- {
- attribute = value;
- }
- }
- public override void Function(String value)
- {
- attribute = value;
- if (Event != null)
- {
- Event(this, new EventArgs());
- }
- }
- public override event EventHandler Event;
- public override Char this[int Index]
- {
- get
- {
- return attribute[Index];
- }
- }
- }
- #endregion
-
- class Program
- {
- static void OnFunction(object sender, EventArgs e)
- {
- for (int i = 0; i < ((DeriveClass)sender).Attribute.Length; i++)
- {
- Console.WriteLine(((DeriveClass)sender)[i]);
- }
- }
- static void Main(string[] args)
- {
- DeriveClass tmpObj = new DeriveClass();
-
- tmpObj.Attribute = "1234567";
- Console.WriteLine(tmpObj.Attribute);
-
- //將靜態函數OnFunction與tmpObj對象的Event事件進行關聯
- tmpObj.Event += new EventHandler(OnFunction);
-
- tmpObj.Function("7654321");
-
- Console.ReadLine();
- }
- }
- }