代理delegate: 對象引用指向某個特定類型的對象。 代理指向某個特定類型的方法。 代理四步: 定義自定義代理類:public delegate void first(int i); 實例化代理類:first MyDelegate = null; 實例添加方法:MyDelegate += new... ...
代理delegate:
對象引用 指向 某個特定類型的對象。
代理 指向 某個特定類型的方法。
代理四步:
- 定義自定義代理類:public delegate void first(int i);
- 實例化代理類:first MyDelegate = null;
- 實例添加方法:MyDelegate += new first(show);
- 通過實例對象調用方法:MyDelegate(666);
class Program
{
//定義frist代理
public delegate void first(int i);
//主函數,main入口
static void Main(string[] args)
{
//創建first類型引用
first MyDelegate = null;
//創建指向show方法的代理引用
MyDelegate += new first(show);
//通過代理引用調用show方法
MyDelegate(666);
Console.ReadKey();
}
//show方法
public static void show(int i)
{
Console.WriteLine(i.ToString());
}
}
- 代理定義在方法外(包括類外)。
- 多重代理返回類型為void。
- 關鍵字delegate。
- 代理可以參數方式傳到方法內部。
如:
class Program
{
//定義frist代理
public delegate void first(int i);
//主函數,main入口
static void Main(string[] args)
{
//創建first類型引用
first MyDelegate = null;
//創建指向show方法的代理引用
MyDelegate += new first(show);
//通過代理引用調用show方法
diao(666, MyDelegate);
Console.ReadKey();
}
//show方法
public static void show(int i)
{
Console.WriteLine(i.ToString());
}
//
public static void diao(int i,first dele)
{
dele(i);
}
}
事件event:
//定義EventDelegate代理
public delegate void EventDelegate();
class Program
{
//主函數,main入口
static void Main(string[] args)
{
//實例化ClockTimer
ClockTimer clockTimer = new ClockTimer();
//MyEvent中添加OnClockTimer方法
clockTimer.MyEvent += new EventDelegate(OnClockTimer);
//執行clickTimer對象的show方法
clockTimer.show();
Console.ReadLine();
}
//接受方法
public static void OnClockTimer()
{
Console.WriteLine("收到時鐘事件");
}
}
//事件產生類
public class ClockTimer
{
//定義事件(event)
public event EventDelegate MyEvent;
//產生事件方法
public void show()
{
for(int i=0;i<1000;i++)
{
//產生事件
MyEvent();
//睡眠1秒
Thread.Sleep(1000);//System.Threading;
}
}
}
- 首先定義代理(類內或者類外定義)。
用delegate關鍵字
- 定義觸發事件(根據代理的作用域來定義)。假如代理定義在program類內部,則把觸發事件寫在program類內部。
用event關鍵字。
- 定義處理觸發事件的方法。
大師們,上面的是我對event和delegate的理解。如果有錯別的地方麻煩您幫我指出來。萬分感謝!