C# 委托 delegate
–委托的内部:(1)方法指针 (2)目标对象 (3)委托链
类似于C中的函数指针,但是是类型安全的。
‘’‘
namespace DelDemo
{
delegate int AddDel(int a, int v); //定义一个委托类型
class Program
{
static void Main(string[] args)
{
#region 多播委托
//多播委托的返回值是最后一个方法的返回值,方法按照委托链依次执行,因此是最后一个方法的结果。
//拿到委托返回值是最后一个委托所指向的方法
AddDel add = new AddDel(Add);
Program pro = new Program();
add += pro.Addinstance;
int e = add(3, 4);
Console.WriteLine(e);//====8
Console.ReadLine();
#endregion
#region 委托的内部构造
//1._methordPtr 方法指针-》指向当前委托指向的方法的内存地址
//2._target 目标对象 静态方法此为空
//3.委托链 委托数组
#endregion
#region 泛型委托
//赋值的几种方式
Func<int, int, int> funcDemo = new Func<int, int, int>(Add);
Func<int, int, int> funcDemo = delegate (int a, int b) { return a + b; };
Func<int, int, int> funcDemo1 = (int x, int y) => { return x + y; };
Func<int, int, int> funcDemo1 = (int x, int y) => x + y;
Func<int, int, int> funcDemo1 = (x, y) => x + y;
Action<int, int> action = delegate (int a, int b)
{
Console.WriteLine(a + b);
};
List<string> strList = new List<string>()
{
"9","32","4","5"
};
var temp =
strList.Where(delegate (string a) { return a.CompareTo("6") < 0; });
foreach (var item in temp)
{
Console.WriteLine(item);
}
#endregion
}
static int Add(int a, int b)
{
return a + b;
}
public int Addinstance(int a, int b)
{
return a + b + 1;
}
}
}
’‘’