网站根目录权限,搭建网站的主要风险,移动应用开发专业,重庆网站建设的价格低匿名函数、参数不固定的函数
匿名函数#xff1a;没有名字#xff0c;又叫做lambda表达式#xff0c;具有简洁#xff0c;灵活#xff0c;可读的特性。
具名函数#xff1a;有名字的函数。
1、简洁性#xff1a;使用更少的代码实现相同的功能
MyDelegate myDelegate…匿名函数、参数不固定的函数
匿名函数没有名字又叫做lambda表达式具有简洁灵活可读的特性。
具名函数有名字的函数。
1、简洁性使用更少的代码实现相同的功能
MyDelegate myDelegate2 delegate (string a) {Console.WriteLine(a);
};
myDelegate2(委托调用匿名函数);//使用Action调用匿名函数
Actionstring action1 delegate (string a) {Console.WriteLine(a);
};
action1(使用Action来调用匿名函数);2、灵活性匿名方法可以作为参数传递给方法也可以当作返回值返回。 //使用Func调用匿名函数Funcint, int, int func1 delegate (int a, int b) {return a b;};Console.WriteLine(func1(100, 200)); //3003、可读性因为代码变少了所以结构更加清晰易懂。
//如果没有参数那么可以进一步的简写
//使用Action调用没有参数的匿名函数
Action greet delegate { Console.WriteLine(这是简写的方法); };
greet();
//lambda表达式本质也是匿名函数也叫箭头函数
Action greet2 () { Console.WriteLine(这是最简单的写法); };
greet2();//使用Func调用匿名函数(箭头函数)
Funcint, int, int func2 (int a, int b) { return a b; };
Console.WriteLine(func2(1, 2));//继续简化根据前面泛型约束传入的类型,后面箭头函数里面就不用写类型了
Funcint, int, int func3 (a, b) { return a b; };
Console.WriteLine(func3(10, 20));匿名函数支持多播(多个委托一起执行)一个委托代表了多个方法
Actionstring test a { Console.WriteLine(test a); };
test a { Console.WriteLine(a); };
test(hello);//testhello hello 执行两次开发当中临时需要一个方法而却方法的使用次数比较少代码结构也比较简单。推荐使用匿名函数。 如果方法的参数不固定可以将参数类型前面添加params修饰符
params string[] string 不管是几个参数只要类型正确都会添加到这个数组中
static string TestMothod(params string[] strings) {string temp ;foreach (var item in strings) {temp item;}return temp;
}//因为使用了params修饰所以数量不固定
Console.WriteLine(TestMothod(1, 2, 3, 4));