1. 程式人生 > >Action與Func 用法

Action與Func 用法

元素 IE sta () 一個 int program spa .com

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 用法