首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# abstract 修飾符完整解析:抽象類別、方法、屬性、事件、索引器統一規範

     編輯:關於C語言

abstract 適用目標

  • 類別、方法、屬性、事件、索引器
  • 表示該成員為抽象,不含實作內容

限制規則

  • 不可與 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

展示抽象屬性、方法、事件、索引器的完整實作流程與多型呼叫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved