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

Visual C# 開發復合控件(二):屬性公開、時間邏輯與自訂事件實作

     編輯:關於C語言

公開子控件屬性

復合控件原則:不直接公開子控件,而是透過包裝屬性暴露必要功能,確保資料封裝與安全性。

唯讀屬性:LabelText

public string LabelText
{
    get { return label1.Text; }
}

可讀寫屬性:LabelBackColor

public Color LabelBackColor
{
    get { return label1.BackColor; }
    set { label1.BackColor = value; }
}

時間顯示邏輯

  1. timer1.Interval = 1000 (1 秒)
  2. Tick 事件:label1.Text = DateTime.Now.ToLongTimeString();
  3. Load 事件啟動:timer1.Enabled = true;

自訂事件:Tick

宣告事件

public event EventHandler Tick;

觸發方法 (慣用 On+EventName 命名)

protected void OnTick(EventArgs e)
{
    if (Tick != null)
        Tick(this, e);
}

在 Timer Tick 中觸發

private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = DateTime.Now.ToLongTimeString();
    OnTick(e);  // 通知容器時間已更新
}

設計重點總結

  • 屬性包裝:控制存取層級、加入驗證邏輯、解耦內部實作
  • 事件模式:標準 EventHandler、OnXxx 保護方法、null 檢查
  • 職責分離:Timer 負責計時,控件負責顯示與通知
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved