C#委托的使用方法
C# 委托的使用方法
1 委托的定义
-
C# 中的委托(Delegate)类似于 C 或 C++ 中函数的 指针 。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类
-
委托的通俗理解
比如您要管您的孩子,把孩子送进了幼儿园,那么.此时您就把您的孩子委托给了幼儿园.当幼儿园放学,将孩子交还给您的手中.则是委托的回调.
当然我这里的例子是说** 异步委托调用**.您也可以同步.
什么是** 同步委托调用**?您去银行存钱.把钱给柜员.他们帮你点钞.存款然后给您存折或卡。那么您就相当于把钱委托给了柜员让他去执行存钱的这个函数.
2 什么时候使用委托
在c#里面,有的时候一些代码的实现必须用到委托,比如:线程里面修改某个textBox的值,如果直接在线程里面写修改的代码,执行时候,编译器会报错,因为c#不允许这样写。还有在单独写的类里面,修改某个form里面某个控件的属性值等等,也是不被允许的。这时候,就需要使用到委托(delegate)。委托其实是这样的,为某些实现写一个函数,并将其赋值给委托(相当于函数指针),在使用 的时候直接通过委托名来调用。
如果我们要把方法当做参数来进行传递的话,就要用到委托。 简单来说,委托是一个类型,这个类型可以赋值一个方法的引用。
3 委托有哪些形式?
委托有delegate、Action、Func、predicate这几种形式。
-
delegate:
delegate是最常使用的一种委托声明,可以传递0-32个参数,可以无返回值也可以指定返回值类型。
例:public delegate int MyDelegate(int a, int b);表示有两个参数,并返回int型。 -
Action:
action是无返回值的泛型委托。可以有0-12个传入的参数,无返回值。
Action 表示无参,无返回值的委托
Action<int,string> 表示有传入参数int,string无返回值的委托
Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托
Action<int,int,int,int> 表示有传入4个int型参数,无返回值的委托
-
Func:
Func是有返回值的泛型委托,可传递0-16个参数。必须有返回值!!!不能为void!!!
Func< int> 表示无参,返回值为int的委托
Func<object,string,int> 表示传入参数为object, string 返回值为int的委托
Func<object,string,int> 表示传入参数为object, string 返回值为int的委托
Func<T1,T2,T3,int> 表示传入参数为T1,T2,T3(泛型)返回值为int的委托
-
predicate:
predicate是返回bool型的泛型委托
predicate 表示传入参数为int 返回bool的委托
Predicate有且只有一个参数,返回值固定为bool
4 委托的语法,使用
- delegate 的使用
public delegate int myDelegate(int a, int b);
private static myDelegate mymethod;
static void Main(string[] args)
{
mymethod= new myDelegate(Sum);
Console.WriteLine(mymethod(10,20));
Console.ReadKey();
}
private static int Sum(int x, int y)
{
return x + y;
}
  这段代码中,实例化了类型为myDelegate的一个委托,mymethod(10,20)等价于使用Sum(10,20)。
- Action 的使用
static void Main(string[] args)
{
Test<string>(Action,"111:");
Test<int>(Action, 1000);
Test<string>(p => { Console.WriteLine("{0}", p); }, "333");//使用Lambda表达式定义委托,这个地方还是有点小问题的。
Console.ReadKey();
}
public static void Test<T>(Action<T> action, T p)
{
action(p);
}
private static void Action(string s)
{
Console.WriteLine(s+"hello");
}
private static void Action(int s)
{
Console.WriteLine(s);
}
- Func 的使用
static void Main(string[] args)
{//Action 的使用
Action<string, string> bookAction = new Action<string, string>(book);
bookAction("一生戎马", "国家图书馆");
//func的使用
//Fun常用有两个参数,前面的是输入参数,后面的是输出参数(意味着是在另一部分运算中产生的)恰恰是整个方法的返回值
Func<string, string> RetBook = new Func<string, string>(retBook);
Console.WriteLine(RetBook("国家战略"));
Console.ReadKey();
}
public static void book(string bookName,string address){
Console.WriteLine("买的书是:{0}", address);
}
public static string retBook(string bookName)
{
return "书的名字是:" + bookName;
}
5 委托的使用流程
使用委托时要先实例化,和类一样,使用new关键字产生委托的新实例,然后将一个或者多个与委托签名匹配的方法与委托实例关联。随后调用委托时,就会调用所有与委托实例关联的方法。
声明和定义委托分为4个步骤:
- 声明一个委托(函数指针)
- 创建委托对象
- 创造符合委托格式的函数。(指针指向的函数)
- 将函数名称赋值给委托。