委託(一個主表單統計多個從表單的按鈕單擊的次數)

來源:互聯網
上載者:User

  最近在學習金老師的《.NET2.0物件導向編程揭秘》,學到了13章,委託、事件驅動和非同步呼叫。書上有個試一試,要求:利用委託,達到一個主表單統計多個從表單的按鈕單擊的次數。

效果如下:

 

frmMain

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Text;
 7 using System.Windows.Forms;
 8 
 9 namespace DelegateInForm
10 {
11     public partial class frmMain : Form
12     {
13         public frmMain()
14         {
15             InitializeComponent();     
16         }
17         private void ShowCount(string count)
18         {
19             lblCount.Text = count;
20         }
21 
22         private void btnClick_Click(object sender, EventArgs e)
23         {
24             //建立從表單對象並顯示
25             frmOther frm = new frmOther();
26             frm.recorder = this.ShowCount;//向從表單的委託變數賦值
27             frm.Show();
28         }
29     }
30 }

 

 

frmOther

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Text;
 7 using System.Windows.Forms;
 8 
 9 namespace DelegateInForm
10 {
11     public partial class frmOther : Form
12     {
13         //定義了一個委託類型ShowInfo
14         public delegate void ShowInfo(string info);
15 
16         public frmOther()
17         {
18             InitializeComponent();
19         }
20         //委託變數recorder
21         public ShowInfo recorder;
22         private static int counter = 0;//計數器,使用static可以多個從表單點擊計數
23         private void btnClickME_Click(object sender, EventArgs e)
24         {
25             counter++;
26             if (recorder != null)
27             {
28                 recorder(counter.ToString());
29             }
30         }
31     }
32 }

之後,我想進一步修改,在一個主表單上單擊按鈕,多個從表單同時顯示單擊的次數。只是對上面的代碼修改了一下,在從表單初始化後,向主表單的委託變數賦值時,出現了錯誤。請大家指教,謝謝。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.