定义
委托是一种数据结构,它引用静态的方法或引用类实例和该类的实例方法。
委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。
委托类型派生自System.Delegate,可使用该类的所有已定义的方法和属性。
具有多个方法的委托派生自System.MulticastDelegate。
委托的类型由委托的名称定义
声明了一个名为delegateProgram的委托:
public delegate int delegateProgram(int x,int y);
特点
1委托是类型安全的;
2允许将方法作为参数进行传递;将方法作为参数进行引用的能力使委托成为定义回调方法的理想选择。
3可用于定义回调方法;
4委托可链接在一起,所以可以对一个事件调用多个方法
举例
由于实例化委托是一个对象,所以可以作为参数传递。
调用委托时,可以调用多个方法:称为多路广播。增加方法可使用“+”添加另外的委托。所增加的方法是按加近来的顺序调用的。也可用“-”移除不要的方法。
如果委托调用近来的一个方法发生异常,而该方法内又没捕获异常,将不再对后面的方法进行调用。
如果委托有返回值,或输出参数,就返回最后那个方法的返回值和参数。
public partial class Default2 : System.Web.UI.Page
{
//声明了一个名为delegateProgram的委托
public delegate string delegateProgram(int a, int b);
public static string Method1(int a, int b)
{//用做加法运算
//在单独类中不能直接用response.write
System.Web.HttpContext.Current.Response.Write("(做了加法运算)");
return Convert.ToString(a + b);
}
public static string Method2(int a, int b)
{//用作乘法运算
System.Web.HttpContext.Current.Response.Write("(做了乘法运算)");
return Convert.ToString(a * b);
}
public void all(int a, int b, delegateProgram xc)//将委托作为一个参数
{
Response.Write(xc(a, b).ToString() + "<br/>");
}
protected void Page_Load(object sender, EventArgs e)
{
delegateProgram d1 = Method1;//把Method1用delegateProgram进行包装,委托给d1
Response.Write("给委托增加方法Method1:");
all(5, 5, d1);//等于将方法Method1作为参数引用
delegateProgram d2 = Method2;
Response.Write("给委托增加方法Method2:");
all(5, 5, d2);
delegateProgram d3 = d1 + d2;//从两个委托中增加两个方法
Response.Write("给委托增加方法Method1和Method2,但将只输出Method2的结果:<br/>");
all(5, 5, d3);
//由委托3可看出虽然只输出了Method2的结果,
//但是也输出了“(做了加法运算)”,说明也调用了Method1
//
}
}