今天在一個項目中看到委托與事件的使用,故重新整理一個簡單易懂的例子,僅供參考而已。
namespace DelegateAndEvent
{
public delegate void delegateTest(int a);//定義一個委托
public delegate void delegateErr(Exception e);//定義一個報錯委托
class Program
{
static void Main(string[] args)
{
object r = Console.ReadLine();
class1 c = new class1();
c.getTest += new delegateTest(c_getTest);//添加事件函數
c.getErr += new delegateErr(c_getError);//添加事件函數
c.start(r);
Console.ReadKey();
}
static void c_getTest(int a)
{
Console.WriteLine("您輸入的數字是:" + a);
}
static void c_getError(Exception e)
{
Console.WriteLine(e.ToString());
}
}
public class class1
{
public event delegateTest getTest = null;//定義一個事件
public event delegateErr getErr = null;//定義一個報錯事件
public class1()
{
}
///
/// 開始執行
///
///
public void start(object a)
{
try
{
if (null != getTest)
{
getTest(Convert.ToInt16(a));
}
}
catch (Exception e)
{
getError(e);
}
}
///
/// 報錯機制
///
///
public void getError(Exception e)
{
if (null != getErr) getErr(e);
}
}
}