Func ,Action , Predicate ,lambda 表达式使用

可参考λ表达式
*1. Func 是内置的delegate 类型
*2. Func 必须有一个返回值
*3. Func 可以有0-16个参数
*4. Func 不能使用ref,out 关键字的引用参数
*5. Func 可以与匿名方法和lambda表达式连用

  • Action 与Func 一样,只是 Action无返回值.

  • Predicate 是只有一个输入参数,且返回值是boolean类型(true,false)的delegate

  • lambda 表达式是匿名方法的一种简化。

  • lambda 表达式是省略匿名方法中的delegate关键字和变量类型并使用goesto"=>" 运算符。

  • Func, Action and Predicate 可以使用lambda表达式。

下面代码示例

using System;
using System.Collections.Generic;
using System.Linq;

namespace test001
{
    class Program
    {
        public delegate int getSum(int x, int y);
        static int sum(int x, int y)
        {
            return x + y;
        }
        static void Main(string[] args)
        {
            // delegate
            getSum getsum = sum;
            Console.WriteLine(sum(4, 5));

            //Func
            Func<int, int, int> add = sum;
            Console.WriteLine(add(4, 5));

            //Func 和匿名方法
            Func<int, int, int> add1 = delegate(int x, int y) { return x + y; };
            Console.WriteLine(add1(4, 5));

            //Func和lambda 表达式,省略delegate,参数类型,使用“=>”运算符
            Func<int, int, int> add2 = (x, y) => { return x + y; };
            Console.WriteLine(add2(4, 5));

            Func<int, int, int> add3 = (x, y) => x + y;
            Console.WriteLine(add3(4, 5));

            Action<string> Print = (string s) => Console.WriteLine(s);
            Print("hello world");

            //lambda表达式 参数为空
            Action P = () => Console.WriteLine("hello world");
            P.Invoke();

            Predicate<string> isEmpty = x => x == string.Empty;
            Console.WriteLine(isEmpty("hello"));

            //list 操作常会用到lambda表达式,主要用于查找元素
            List<int> list = new List<int> { 23, 12, 89, 34 };
            int oddint = list.FindIndex(x => x % 2 == 0);
            Console.WriteLine(oddint);
            Console.ReadLine();
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值