委托 Delegate
什么是委托?
委托是一个类,在实例化委托时,可以将委托的实例与具有相同返回值类型的方法相关联,这样就可以通过委托来调用方法。另外,使用委托还可以将方法作为参数传递给其他方法。
委托的使用
- 声明委托
- 有一个或以上与委托具有相同类型的返回值和参数,且参数个数相同的方法。
- 实例化委托,使用 new 关键字。
- 调用委托
示例:
using System;
namespace 委托的同步_异步
{
//1.声明委托
public delegate void DelPrintln(string msg);
class Program
{
static void Main(string[] args)
{
//3.实例化委托
DelPrintln println = new DelPrintln(Println);
//4.调用委托
println("我是委托");
Console.ReadKey();
}
//2.写一个与委托返回值类型相同,参数类型和个数相同的方法
static void Println(string text)
{
Console.WriteLine(text);
}
}
}
泛型委托
- Action 没有返回值的泛型委托
示例1:没有参数没有返回值的泛型委托
using System;
namespace 委托的同步_异步
{
class Program
{
static void Main(string[] args)
{
//1.声明没有参数没有返回值的泛型委托
Action action1;
//3.给泛型委托赋值
action1 = new Action(M1);
//4.调用泛型委托
action1();
Console.ReadKey();
}
//2.写一个没有参数没有返回值的方法
static void M1()
{
Console.WriteLine("我是没有参数没有返回值的方法");
}
}
}
示例2:一个参数为 string 类型没有返回值的泛型委托
using System;
namespace 委托的同步_异步
{
class Program
{
static void Main(string[] args)
{
//1.声明没有参数没有返回值的泛型委托
Action<string> action1 ;
//3.给泛型委托赋值
action1 = new Action<string>(M1);
//4.调用泛型委托
action1("我是有一个参数类型为string类型的没有返回值的方法");
Console.ReadKey();
}
//2.写一个参数为string类型没有返回值的方法
static void M1(string msg)
{
Console.WriteLine(msg);
}
}
}
- Func 有返回值的泛型委托
实例1:两个参数为 int ,返回值为 int 的泛型委托
using System;
namespace 委托的同步_异步
{
class Program
{
static void Main(string[] args)
{
//1.声明
Func<int, int, int> func;
//2.赋值
func = new Func<int, int, int>(Add);
//3.调用
int sum = func(1,2);
Console.WriteLine(sum);
Console.ReadKey();
}
//2.写一个有两个int参数且返回值为int的方法
static int Add(int a,int b)
{
return a + b;
}
}
}
匿名方法 Lambda表达式
using System;
namespace 委托的同步_异步
{
class Program
{
static void Main(string[] args)
{
Action action1 = Test;
action1();
Action action2 = delegate() { Console.WriteLine("匿名方法"); } ;
action2();
Action action3 = () => { Console.WriteLine("Lambda表达式"); };
action3();
Func<int, int, int> func1 = Add;
func1(1,1);
Func<int, int, int> func2 = delegate (int a, int b) { return a + b; };
func2(2,2);
Func<int, int, int> func3 = (int a, int b) => { return a + b; };
func3(3,3);
Console.ReadKey();
}
static void Test()
{
Console.WriteLine("Test方法");
}
static int Add(int a,int b)
{
return a + b;
}
}
}
多播委托
一个委托可以关联一个或多个方法,当委托中只有一个关联方法称为单播委托,当委托关联多个方法称为多播委托。
实例:
using System;
namespace 委托的同步_异步
{
class Program
{
static void Main(string[] args)
{
Action action1 = Test1;
action1 += Test2;
action1 += Test3;
action1();
Console.ReadKey();
}
static void Test1()
{
Console.WriteLine("Test1方法");
}
static void Test2()
{
Console.WriteLine("Test2方法");
}
static void Test3()
{
Console.WriteLine("Test3方法");
}
}
}