匿名方法:通过匿名委托 、lamada表达式定义的函数具体操作并复制给委托类型;
匿名委托:委托的一种简单化声明方式通过delegate关键字声明;
内置泛型委托:系统已经内置的委托类型主要是不带返回值的Action<T1,,,,Tn>和带返回值的Func<T1,,,Tn,Tresult>
实例代码(运行环境netcoreapp3.1)
class demoFunc { /// <summary> /// 定义函数单条语句直接用lamada表达式 /// </summary> /// <param name="x"></param> public void funcA( string x)=> Console.WriteLine("this is funcA!{0}",x); /// <summary> /// 使用内置泛型委托action(返回值为void) 定义委托类型成员变量,并通过那lamada定义匿名函数 /// </summary> public Action<string> funcB= x => Console.WriteLine("this is funcB!{0}", x); /// <summary> /// 使用内置泛型委托action(返回值为void) 定义委托类型成员变量, /// 并通过匿名委托定义匿名函数 /// </summary> public Action<string> FuncB_1= delegate(string s) { Console.WriteLine("this is funcB_1!{0}", s); }; /// <summary> /// 定义委托类型 /// </summary> /// <param name="s"></param> public delegate void TFuccB_2(string s); /// <summary> /// 使用匿名函数声明委托 /// </summary> public TFuccB_2 FuncB_2= delegate(string s) { Console.WriteLine("this is funcB_2!{0}", s); }; /// <summary> /// 使用内置泛型委托func(返回值不可以为void,参数列表中最后一个时返回值), /// 定义委托类型成员变量,并通过lamada定义单含带返回值的匿名函数 /// 单行表达式的返回值就是此匿名函数的返回值 /// </summary> public Func<string, string> funcC=x=> string.Format("this is funcC!{0}", x); /// <summary> /// 使用内置泛型委托func(返回值不可以为void),定义委托类型成员变量, /// 并通过lamada定义多行代码的匿名函数 /// </summary> public Func<string,string, string> funcD= (x1, x2) => { Console.WriteLine("this is funcd!{0}{1}", x1, x2); return string.Format("this is funcd!{0}{1}", x1, x2); }; }
运行测试代码
static void Main(string[] args) { demoFunc demo=new demoFunc(); demo.funcA("a"); demo.funcB("b"); demo.FuncB_1("b"); demo.FuncB_2("b"); Console.WriteLine(demo.funcC("c")); Console.WriteLine(demo.funcD("d1","d2")); Console.WriteLine("Hello World!"); }
运行结果
1 "C:\Program Files\dotnet\dotnet.exe" C:/Users/edzjx/RiderProjects/testDemo/testDemo/bin/Debug/netcoreapp3.1/testDemo.dll 2 this is funcA!a 3 this is funcB!b 4 this is funcB_1!b 5 this is funcB_2!b 6 this is funcC!c 7 this is funcd!d1d2 8 this is funcd!d1d2 9 Hello World! 10 11 Process finished with exit code 0. 12