当前位置: 代码迷 >> 综合 >> C#的委托
  详细解决方案

C#的委托

热度:73   发布时间:2023-09-18 21:22:13.0

C#的委托即为可以包装函数的一个“类”,能够间接调用函数。

定义返回值为void,无参类型的委托。如下列代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DelegateExample
{delegate void MyDele();class Program{static void Main(string[] args){MyDele myDele = new MyDele(SayHello);myDele+=SayHello;myDele.Invoke();myDele();}public static void SayHello() {Console.WriteLine("Hello");}}
}

这里就定义了一个名为MyDele的委托,这个委托能接受返回值为void,无参的函数,即委托的定义中包括该委托能接受的函数类型。注意使用时,只写函数名,不写函数后的(),委托不仅能接受一个同类型的函数,还能接受多个,例如上述中就使用+=再添加了一个函数SayHello,委托的调用有两种方法,一种是使用invoke函数调用,第二种是直接像函数的调用,直接加括号调用。一般都使用第二种方法。

 

 

定义返回值为int,参数为两个int类型的委托。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DelegateExample
{delegate int MyDele(int x,int y);class Program{static void Main(string[] args){MyDele myDele = new MyDele(Add);int z = myDele(3, 4);Console.WriteLine(z);}public static int Add(int x,int y){return x + y;}}
}

 

 

系统有两个定义好的委托,分别为Action委托和Func委托,Action委托默认为返回值为void类型的委托,Func即为带范围值的委托。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DeleEx
{class Program{static void Main(string[] args){Action<string> action = SayHello;action("Alice");Func<int, int, int> func = Add;var x = func(2, 3);Console.WriteLine(x);}static void SayHello(string str){Console.WriteLine("Hello,{0}",str);}static int Add(int a,int b){return a + b;}}
}

 

  相关解决方案