正式进入C#的世界——委托

时间:2023-03-09 17:53:04
正式进入C#的世界——委托

委托(delegate)1、可以认为是这样的对象,它包含具有相同签名和返回值类型的有序方法列表。2、可以理解为函数的一个包装,它使得C#中的函数可以作为参数来被传递。

委托的定义和方法的定义类似,只是在定义的前面多一个delegate关键字。

public delegate void MyDelegate( int para1, string para2);
//包装
public void MyMethod(int a, string b); //返回类型相同,参数个数,顺序和类型相同。
  • 方法的签名 必须 与 委托 一致,方法签名包括参数的个数、类型和顺序。
  • 方法的返回类型要和 委托 一致,注意,方法的返回类型不属于方法签名的一部分。
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks; namespace 作业1
    {
    class Program
    {
    //1.使用delegate定义一个委托类型
    delegate void MyDelegate(int para1, int para2);
    static void Main(string[] args)
    { //2.声明委托变量d
    MyDelegate d; //3.实例化委托类型,传递的方法也可以为静态方法,这里传递的是实例方法
    d=new MyDelegate(new Program().Add); //4.委托类型作为参数传递给另一个方法
    MyMethod(d);
    Console.ReadKey();
    } //该方法的定义必须与委托定义相同,即返回类型为void,两个int类型的参数
    void Add(int para1,int para2)
    {
    int sum = para1 + para2;
    Console.WriteLine("两个值的和为:"+sum);
    } //方法的参数是委托类型
    private static void MyMethod(MyDelegate mydelegate)
    {
    //5. 在方法中调用委托
    mydelegate(, );
    } }
    }

    委拖链

委托链其实就是委托类型,只是委托链把多个委托链接在一起而已,也就是说,我们把链接了多个方法的委托称为委托链或多路广播委托。

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 作业1
{
class Program
{
public delegate void DelegateTest();
static void Main(string[] args)
{ //用静态方法实例化委托
DelegateTest dtDelegate = new DelegateTest(Program.method1); //用实例方法
DelegateTest deDelegate1 = new DelegateTest(new Program().method2); //定义一个委托对象,一开始指定为空,即不代表什么方法
DelegateTest delegateChain = null; //使用+符号链接委拖 -符号移除委托
delegateChain += dtDelegate;
delegateChain += deDelegate1;
delegateChain += deDelegate1;
delegateChain += dtDelegate;
delegateChain-= dtDelegate;
delegateChain(); Console.ReadKey();
} //静态方法
private static void method1()
{
Console.WriteLine("这里是静态方法");
} private void method2()
{
Console.WriteLine("这里是实例方法");
}
}
}