using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Csharp控制臺練習{class Program{//【1】、聲明委托 (定義一個函數的原形:返回值+參數類型和個數)public delegate int DemoDelegate(int a, int b);//【2】、要存放的方法等具體實現功能(比如加減法)static int Add(int a, int b) { return a + b; }static int Sub(int a, int b) { return a - b; }static void Main(string[] args){//【3】、定義委托變量,并且關聯要存放于該變量的方法DemoDelegate objDel = new DemoDelegate(Add);//【4】、通過委托調用方法,而不是直接調用方法Console.WriteLine( objDel(10, 20));objDel -= Add;objDel += Sub;Console.WriteLine( objDel(10, 20));Console.ReadKey();}}
}
此程序輸出結果為30 ? ? -10.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace Csharp窗體練習
{public partial class frmOther1 : Form{public frmOther1(){InitializeComponent();}public void Receive(string counter){labCounter.Text = counter;}}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace Csharp窗體練習
{public delegate void ShowCounterDele(string counter);//【1】聲明個委托,一般在類外面聲明public partial class Form1 : Form{ShowCounterDele showCounterdel; //【2】定義委托對象public Form1(){InitializeComponent();frmOther frmother = new frmOther();frmOther1 frmother1 = new frmOther1();frmOther2 frmother2 = new frmOther2();showCounterdel += frmother.Receive; //【3】將委托對象與方法關聯起來showCounterdel += frmother1.Receive;showCounterdel += frmother2.Receive;frmother.Show();frmother1.Show();frmother2.Show();}private int count = 0;private void btnCounter_Click(object sender, EventArgs e){count++;showCounterdel(count.ToString()); //【4】、通過委托調用方法}private void btnClear_Click(object sender, EventArgs e){count=0;showCounterdel(count.ToString());}}
}
執行上面程序,點擊主窗體中的按鈕,從窗體會顯示單擊次數。點擊主窗體的復位按鈕然后計數歸零。