C#沉淀之委托的深入讲解

2020-01-05 09:37:19刘景俊

具有引用参数的委托


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeForDelegate
{
 //定义委托类型
 delegate void MyDel(ref int x);
 class Program
 {

  static void Add1(ref int x) { x += 1; }
  static void Add2(ref int x) { x += 2; }

  static void Main(string[] args)
  {
   Program program = new Program();

   MyDel del = Add1;
   del += Add2;

   //ref会将x当作引用值传递给委托方法
   int x = 5;
   del(ref x);

   Console.ReadKey();
  }
 }
}

在调用Add1方法时,x = 5+1,再调用Add2方法时,不是x = 5+2而是x = 6 +2

参考:ref按引用传递参数

在方法的参数列表中使用 ref 关键字时,它指示参数按引用传递,而非按值传递。 按引用传递的效果是,对所调用方法中参数进行的任何更改都反映在调用方法中。 例如,如果调用方传递本地变量表达式或数组元素访问表达式,所调用方法会替换 ref 参数引用的对象,然后,当该方法返回时,调用方的本地变量或数组元素将开始引用新对象

匿名方法

匿名方法是在初始化委托时内联声明的方法


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeForDelegate
{
 //定义委托类型
 delegate void MyDel(ref int x);
 class Program
 {

  static void Add1(ref int x) { x += 1; }
  static void Add2(ref int x) { x += 2; }

  static void Main(string[] args)
  {
   Program program = new Program();
   
   //采用匿名方法形式代替具名方法
   MyDel del = delegate(ref int y) { y += 3; };
   del += Add1;
   del += Add2;

   //ref会将x当作引用值传递给委托方法
   int x = 5;
   del(ref x);

   Console.ReadKey();
  }
 }
}

在声明委托变量时作为初始化表达式,或在为委托增加事件时使用