C#—委托的使用

委托

委托实际为一种 中间人 ,A需要C去做某件事情 而由B去调用C来做事。

1.委托是一种类型,它可以声明在类的外部,也可以在类内部声明。

public delegate void NoParaNoRenturnOutClass();//类外部委托
class MyDelegate
{
public delegate void NoParaNoReturn();//类内部委托
}

2.委托对应方法,需要与绑定的方法有 相同数量 、相同类型 、相同返回值 才能绑定。

  • 如此 是一个 无参数 无返回值 委托和方法绑定
public delegate void NoParaNoReturn(); //无参数 无返回值
class MyDelegate {
     private static void ShowSomething()  //无参数无返回值的方法
    {
          Console.WriteLine("这里是SonmeThing");
     }

   public static void Show()
    {
         NoParaNoReturn method = new NoParaNoReturn(ShowSomething);//委托的实例化
         method.Invoke();//委托实例调用
    }
}
  • 如此 是一个 有参数 无返回值 委托和方法绑定
public delegate void WhitParaNoReturn(string name); //有参数无返回值的委托
class MyDelegate {
    private static void ShowAnything(string a)
    {
        Console.WriteLine("这里是Anything:{0}",a);
    }

    public static void Show()
    {
        WhitParaNoReturn method2 = new WhitParaNoReturn(ShowAnything); //方法绑定
        method2("黑"); //调用委托
    }
}
  • 有参数 有返回值 委托和方法绑定
public delegate int WithParaWithReturn(int a);有参数 有返回值
class MyDelegate {
     private static int Showthing(int a)
     {
        Console.WriteLine("这里是Anything:{0}", a);
        return a;
     }

    public static void Show()
    {
        WithParaWithReturn method2 = new WithParaWithReturn(Showthing); //方法绑定
       Console.WriteLine(method2(200)); //调用委托 将会返回得到 200
    }
}

多播委托

  • 如下 最终的返回值仅为 return 出的 100
public delegate int WithParaWithReturn(int a);有参数 有返回值
class MyDelegate {
    private static int ShowGetthing()
    {
        Console.WriteLine("展示");
        return 100;
    }

    public static void Show()
    {
     //多播委托 最终值为单一值 100
        NoParaWhitReturn noParaWhitReturn = new NoParaWhitReturn(ShowGetthing);
        noParaWhitReturn += ShowGetthing;
        noParaWhitReturn += ShowGetthing;
        noParaWhitReturn += ShowGetthing;

        Console.WriteLine(noParaWhitReturn());
    }
}

自带委托 Action

  • Action 为C#自带的委托类型 无需另外声明委托,可 直接创建一个委托实例
  • Action 为无返回值的委托类型
class MyDelegate {
     private static void ShowSomething()  //无参数无返回值的方法
    {
          Console.WriteLine("这里是SonmeThing");
     }

   public static void Show()
    {
        Action action1 = new Action(ShowSomething);
        action1();//委托实例调用   无参数 无返回值

        Action action2 = new Action(ShowAnything);
        action2("王");  // 有参数 无返回值  此时参数类型必须标明在声明委托中
    }
}

自带委托Func

  • Func 为C#自带的委托类型 无需另外声明委托,可 直接创建一个委托实例
  • Func 为有返回值的委托类型
class MyDelegate {
     private static void ShowSomething()  //无参数无返回值的方法
    {
          Console.WriteLine("这里是SonmeThing");
     }

   public static void Show()
    {
          Func fun1 = new Func(ShowGetthing);
          fun1();//委托实例调用   无参数 有返回值

          Func fun2 = new Func(Showthing);
          fun2(100);  // 有参数 有返回值  Func中的参数类型、返回值类型都需要标明,在泛型类型声明中 当有返回值时候,最后一个参数类型为返回值类型
    }
}

你可能感兴趣的:(C#—委托的使用)