码迷,mamicode.com
首页 > 其他好文 > 详细

Action与Func 用法

时间:2018-04-20 12:16:15      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:add   分享   .com   read   except   ring   key   ret   string   

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

namespace ActionFunc
{

    //Action与Func 都是  net内置泛型委托.

    //1 Action  没返回值 , 2 Func  有返回值
   static class Program
   {
        static void Main(string[] args)
        {

               //func 简单Lambda用法
               Func<int> f1 = () => {
                        return 10;
               };
               Console.WriteLine(f1());

 

               //func 简单Lambda用法2
               Func<string, int, string> f2 = (x, y) =>
               {
                          return x + y;
               };
              Console.WriteLine(f2("你好",666));

 

              //action 简单Lambda用法
              Action<int, int> ac1 = (x, y) =>
              {
                    Console.WriteLine("{0}*{1}={2}",x,y, x * y);
              };
              ac1(10, 99);


              //action使用
              Actiontmp<int, int>((t1, t2) => { Console.WriteLine("Actiontmp:{0}+{1}={2}", t1, t2, t1 + t2); }, 12, 15);


 


              //初始值
              List<int> list = new List<int>() { 10, 22, 2, 5, 89, 75 };

              //func用法获取 实体
             try {
                  var entity = list.GetEntity(m => m > 100);
                  Console.WriteLine(entity);
              }
             catch {
                  var d = 222;
             }

             //func用法获取 列表
             var nlist = list.GetSelect(m => m > 6);
             foreach (var entity in nlist)
             {
                 Console.WriteLine(entity);
             }
             Console.ReadKey();
   

     }

     //func用法获取 实体
     public static TData GetEntity<TData>(this IEnumerable<TData> list, Func<TData, bool> func)
     {
            foreach (TData entity in list)
            {
                  if (func(entity))
                  {
                       return entity;
                  }
           }

            throw new Exception("不存在满足条件的第一个元素!");
            //return ;
     }

      //func用法获取 列表
      public static List<TData> GetSelect<TData>(this IEnumerable<TData> list, Func<TData, bool> func)
      { 
               List<TData> nlist = new List<TData>();
               foreach (TData entity in list)
               {
                         if (func(entity))
                         {
                                nlist.Add(entity);
                         }
                }
                return nlist;
       }

       //action使用
       public static void Actiontmp<T1,T2>(Action<T1,T2> act, T1 t1, T2 t2) {
                       act(t1, t2);
       }


  }


}

 

 

技术分享图片

Action与Func 用法

标签:add   分享   .com   read   except   ring   key   ret   string   

原文地址:https://www.cnblogs.com/chxl800/p/8889591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!