一、关于委托的回顾
委托其实相当于C++里面的函数指针。官方描述是:委托是方法的类型安全的引用。
1、普通委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
//delegate定义的是一个类型,这个类型变量的值是签名相同的函数
delegate char getCharFromString(string str, int index);
class Program
{
static void Main(string[] args)
{
//定义一个getCharFromString(delegate)型的变量,并为其赋值。赋值的条件是:签名相同
getCharFromString fac = get;
//通过委托调用函数功能
Console.WriteLine(fac("yuyong", 2));
getCharFromString facNext = getNext;
Console.WriteLine(facNext("yuyong", 2));
Console.ReadKey();
}
static char get(string str, int index)
{
return str.ToArray()[index];
}
static char getNext(string str, int index)
{
return str.ToArray()[index + 1];
}
}
}
2、Func委托
Func委托是一种泛型委托,例如,上面的delegate char getCharFromString(string str, int index);等价于Func<string,int, char>
定义Func的类型列表最后一个类型是返回值类型,前面的类型都是输入参数类型。如果类型列表只有一个类型,那这个类型就是返回类型。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
delegate char getCharFrom