abstract 修飾符可以用于類棚辽、方法兢孝、屬性、事件和索引指示器(indexer)睬捶,表示其為抽象成員
abstract 不可以和 static 黔宛、virtual 一起使用
聲明為 abstract 成員可以不包括實(shí)現(xiàn)代碼,但只要類中還有未實(shí)現(xiàn)的抽象成員(即抽象類)擒贸,那么它的對象就不能被實(shí)例化臀晃,通常用于強(qiáng)制繼承類必須實(shí)現(xiàn)某一成員
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
namespaceExample04
{
#region基類觉渴,抽象類
publicabstractclassBaseClass
{
//抽象屬性,同時具有g(shù)et和set訪問器表示繼承類必須將該屬性實(shí)現(xiàn)為可讀寫
publicabstractString Attribute
{
get;
set;
}
//抽象方法积仗,傳入一個字符串參數(shù)無返回值
publicabstractvoidFunction(Stringvalue);
//抽象事件疆拘,類型為系統(tǒng)預(yù)定義的代理(delegate):EventHandler
publicabstracteventEventHandler Event;
//抽象索引指示器,只具有g(shù)et訪問器表示繼承類必須將該索引指示器實(shí)現(xiàn)為只讀
publicabstractCharthis[intIndex]
{
get;
}
}
#endregion
#region繼承類
publicclassDeriveClass : BaseClass
{
privateString attribute;
publicoverrideString Attribute
{
get
{
returnattribute;
}
set
{
attribute =value;
}
}
publicoverridevoidFunction(Stringvalue)
{
attribute =value;
if(Event !=null)
{
Event(this,newEventArgs());
}
}
publicoverrideeventEventHandler Event;
publicoverrideCharthis[intIndex]
{
get
{
returnattribute[Index];
}
}
}
#endregion
classProgram
{
staticvoidOnFunction(objectsender, EventArgs e)
{
for(inti = 0; i < ((DeriveClass)sender).Attribute.Length; i++)
{
Console.WriteLine(((DeriveClass)sender)[i]);
}
}
staticvoidMain(string[] args)
{
DeriveClass tmpObj =newDeriveClass();
tmpObj.Attribute ="1234567";
Console.WriteLine(tmpObj.Attribute);
//將靜態(tài)函數(shù)OnFunction與tmpObj對象的Event事件進(jìn)行關(guān)聯(lián)
tmpObj.Event +=newEventHandler(OnFunction);
tmpObj.Function("7654321");
Console.ReadLine();
}
}
}
結(jié)果:
1234567
7
6
5
4
3
2
1