static、virtual 同時使用
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);
// 抽象事件:使用系統預定義 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 => attribute;
set => attribute = value;
}
public override void Function(string value)
{
attribute = value;
Event?.Invoke(this, new EventArgs());
}
public override event EventHandler Event;
public override char this[int Index] => attribute[Index];
}
#endregion
class Program
{
static void OnFunction(object sender, EventArgs e)
{
var obj = (DeriveClass)sender;
for (int i = 0; i < obj.Attribute.Length; i++)
Console.WriteLine(obj[i]);
}
static void Main(string[] args)
{
DeriveClass tmpObj = new DeriveClass();
tmpObj.Attribute = "1234567";
Console.WriteLine(tmpObj.Attribute);
tmpObj.Event += new EventHandler(OnFunction);
tmpObj.Function("7654321");
Console.ReadLine();
}
}
}
1234567
7
6
5
4
3
2
1
展示抽象屬性、方法、事件、索引器的完整實作流程與多型呼叫。