一、委托——一种在对象里保存方法引用的类型,一种类型安全的函数指针;
优点:1、压缩调用匿名方法;2、合理的使用委托可以提高程序性能
声明:public delegate type_of_delegate delegate_name () 形式来声明
eg:public delegate void Delegate_Multicast(int x,int y);
注:1、遵循和声明方法一样的语法来声明委托;2.、可以不带参数或参数列表的情况下声明委托
示例程序:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public
delegate
double
Delegate_Prod(
int
a ,
int
b);
static double fn_Prodvalues( int val1, int val2)
{
return val1 * val2;
}
static void Main( string [] args)
{
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.WriteLine( " Place Enter Values " );
int v1 = Int32.Parse(Console.WriteLine());
int v2 = Int32.Parse(Console.WriteLine());
double rs = delObj(v1, v2);
Console.WriteLine( " Result: " + rs);
Console.ReadLine();
}
static double fn_Prodvalues( int val1, int val2)
{
return val1 * val2;
}
static void Main( string [] args)
{
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.WriteLine( " Place Enter Values " );
int v1 = Int32.Parse(Console.WriteLine());
int v2 = Int32.Parse(Console.WriteLine());
double rs = delObj(v1, v2);
Console.WriteLine( " Result: " + rs);
Console.ReadLine();
}
在Main 方法中,首先创建一个委托实例,如下,此时将函数名称传递给委托实例
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
之后,程序接收用户输入的两个值,并将其传递个委托
delObj(v1, v2);
在这个委托对象中,压缩了方法的功能并返回我们在方法中指定的结果。
二、多播委托
注:1、多播委托包括一个以上的方法引用;2、多播委托包含的方法必须返回void,否则程序会抛出run-time exception
多播委托示例程序:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
delegate
void
Delegate_Multicast(
int
x,
int
y);
class TestMulDelegate
{
static void Method1( int x, int y)
{
Console.WriteLine( " You are in Method1 " );
}
static void Method2( int x, int y)
{
Console.WriteLine( " You are in Method2 " );
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func( 1 , 2 );
func -= new Delegate_Multicast(Method1);
func( 2 , 3 );
Console.ReadLine();
}
}
class TestMulDelegate
{
static void Method1( int x, int y)
{
Console.WriteLine( " You are in Method1 " );
}
static void Method2( int x, int y)
{
Console.WriteLine( " You are in Method2 " );
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func( 1 , 2 );
func -= new Delegate_Multicast(Method1);
func( 2 , 3 );
Console.ReadLine();
}
}
在多播委托对象中使用+=来添加委托,使用-=移除委托