C# 委托——delegate
委托是方法的抽象,它存储的就是一系列具有相同签名和返回回类型的方法的地址;
简单理解:
委托从字面上理解就是一种代理,类似于房屋中介,由租房人委托中介为其租赁房屋。
使用步骤“
委托在使用时遵循三步走的原则,即定义声明委托、实例化委托以及调用委托。
委托是 C# 语言中的一个特色,通常将委托分为命名方法委托、多播委托、匿名委托,其中命名方法委托是使用最多的一种委托。
语法:
修饰符 delegate 返回值类型 委托名 ( 参数列表 );
实例化委托的语法
委托名 委托对象名 = new 委托名 ( 方法名 );
实例化委托后即可调用委托
委托对象名 ( 参数列表 );
基础用法:
public class FuncClass
{
//第一步:定义一个委托
//修饰符 delegate 返回值类型 委托名 ( 参数列表 );
public delegate string Mydelegate();
public delegate string Mydelegate1(int a,int b,int c);
public static void getinit()
{
//第二步:实例化委托
//委托名 委托对象名 = new 委托名 ( 方法名 );
Mydelegate mydelegate = new Mydelegate(returnstring);
//第三步:调用委托
//委托对象名 ( 参数列表 );
mydelegate();
Console.WriteLine(mydelegate());
Mydelegate1 mydelegate1 = new Mydelegate1(returnint);
Console.WriteLine(mydelegate1(1,2,3));
}
public static string returnstring()
{
return "测试返回string类型的Func";
}
public static string returnint(int a,int b,int c)
{
int d= a + b + c;
return d.ToString() ;
}
}
demo:
public class FuncClass
{
//第一步:定义一个委托
//修饰符 delegate 返回值类型 委托名 ( 参数列表 );
public delegate string Mydelegate1(Func<int,int,int,int> func);
public static void getinit()
{
//第二步:实例化委托
//委托名 委托对象名 = new 委托名 ( 方法名 );
Mydelegate1 mydelegate2 = new Mydelegate1(returnint);
//第三步:调用委托
//委托对象名 ( 参数列表 );
mydelegate2((a, b, c) => a * b * c);
Console.WriteLine(mydelegate2((a, b, c) => a * b * c));
}
public static string returnstring()
{
return "测试返回string类型的Func";
}
public static string returnint(int a, int b, int c)
{
int d = a + b + c;
return d.ToString();
}
//Func<int,int,int,int> func:lambda表达式
public static string returnint(Func<int,int,int,int> func)
{
string a="";
for (int i = 0; i < 10; i++)
{
Console.WriteLine( func(i, i + 2, i + 4));
a = func(i, i + 2, i + 4).ToString();
}
return a;
}
}
demo:
多播委托
public class FuncClass
{
//第一步:定义一个委托
//修饰符 delegate 返回值类型 委托名 ( 参数列表 );
public delegate string Mydelegate();
public static void getinit()
{
//第二步:实例化委托
//委托名 委托对象名 = new 委托名 ( 方法名 );
Mydelegate mydelegate1 = new Mydelegate(returnint01);
//多播委托
mydelegate1 += returnint02;
mydelegate1 += returnint03;
mydelegate1 += returnint03;
mydelegate1 += returnint03;
mydelegate1 -= returnint03;
//多播委托数组
Delegate[] delegates = mydelegate1.GetInvocationList();
foreach (Mydelegate dd in delegates)
{
//执行委托
Console.WriteLine(dd());
}
}
public static string returnint01()
{
return "测试多播委托";
}
public static string returnint02()
{
return "测试多播委托+";
}
public static string returnint03()
{
return "测试多播委托-";
}
}