c# 委托(Func、Action)
以前自己写委托都用 delegate, 最近看组里的大佬们都用 Func , 以及 Action 来实现, 代码简洁了不少, 但是看得我晕晕乎乎。 花点时间研究一下,记录一下,以便后期的查阅。
1、Func 用法 (封装方法,传入参数, 有返回值)
Func<in T1, in T2, ..., out TResult> (T1, T2, ...)
封装一个方法,该方法有 (0 /1/2/3 ... 16)个参数,且返回由 TResult 参数指定的值的类型。
public static void Main()
{
// 方法一: Func 相当于系统内置的 委托
Func<int, int, string> method = Calculate; // 方法二: 调用 Lambda 方法实现, 更简洁
Func<int, int, string> method_1 = (x, y) =>
{
int val = x + y;
return string.Format("the calculate {0} plus {1} result is: {2}", x, y, val);
}; Console.WriteLine(method(, ));
Console.WriteLine(method_1(, ));
Console.ReadLine();
} public static string Calculate(int x, int y)
{
int val = x + y;
return string.Format("the calculate {0} plus {1} result is: {2}", x, y, val);
}
2、Action 用法 (封装一个方法, 传入参数, 无返回值)
Action<T1, T2, T3, ...>(t1, t2, t3 ...)
封装一个方法, 该方法传入 (0/1/2 ...) 个参数, 且不返回值。
public static void Main()
{
Method_First("Hi, Here!");
Method_First("Hi, There!"); Console.ReadLine();
} private static void Method_First(string y)
{
Action<string> method;
method = x => { Console.WriteLine("the input message is: {0}", x); };
method(y);
} private static void Method_Sec(string y)
{
Action<string> method = x => { Console.WriteLine("the input message is : {0}", x); };
method(y);
}
3. 委托的使用
讲了两种不同情况的委托, 那么什么时候使用委托呢?
根据官方文档,在以下情况下,请使用委托:
当使用事件设计模式时。
当封装静态方法可取时。
当调用方不需要访问实现该方法的对象中的其他属性、方法或接口时。
需要方便的组合。
当类可能需要该方法的多个实现时。
4. 在 Task 使用委托
Task 表示一个异步操作。
public static void Main()
{
// 启动方法1
Task t = Task.Run(() =>
{
Thread.Sleep();
Console.WriteLine("First task finished time is:{0}", DateTime.Now.ToString());
}); // 方法2
Task t_2 = Task.Factory.StartNew(() => {
Thread.Sleep();
Console.WriteLine("second task finished time is:{0}", DateTime.Now.ToString());
}); // 方法 3
Action action = () =>
{
Thread.Sleep();
Console.WriteLine("third task finished time is:{0}", DateTime.Now.ToString());
};
Task.Factory.StartNew(action).ContinueWith(thirdTask =>
{
if (thirdTask.IsCompleted)
{
Console.WriteLine("the third task has finished");
}
else if (thirdTask.IsFaulted)
{
Console.WriteLine(thirdTask.Exception);
}
}); Console.WriteLine("main thread has end:{0}",DateTime.Now.ToString() ); Console.ReadKey();
}
运行结果如下 :
main thread has end:2018-03-04 22:03:39
First task finished time is:2018-03-04 22:03:40
second task finished time is:2018-03-04 22:03:41
third task finished time is:2018-03-04 22:03:42
the third task has finished
c# 委托(Func、Action)的更多相关文章
- 委托、多播委托、泛型委托Func,Action,Predicate,ExpressionTree
当试图通过一个事件触发多个方法,抽象出泛型行为的时候,或许可以考虑使用委托. 通过委托构造函数或委托变量把方法赋值给委托 private delegate double DiscountDel ...
- C#系统委托之Action And Func
Action Action<T> Func Func<T> Action:封装一个方法,该方法不具有参数并且不返回值 public delegate void Action() ...
- C#中常见的委托(Func委托、Action委托、Predicate委托)
今天我要说的是C#中的三种委托方式:Func委托,Action委托,Predicate委托以及这三种委托的常见使用场景. Func,Action,Predicate全面解析 首先来说明Func委托,通 ...
- Func 委托 和 Action 委托 初步谈论
继上篇EventHandler之后,继续填坑,简单了解下Func<TResult> 委托 和 Action 委托. msdn对于两者的解释: Func<TResult>:封装一 ...
- 委托, 泛型委托,Func<T>和Action<T>
使用委托来做一些事情,大致思路是: 1.定义声明一个委托,规定输入参数和输出类型.2.写几个符合委托定义的方法.3.把方法列表赋值给委托4.执行委托 internal delegate int MyD ...
- [C#学习笔记]Func委托与Action委托
学习一项新知识的时候,最好的方法就是去实践它. 前言 <CLR via C#>这本神书真的是太有意思了!好的我的前言就是这个. Fun 如果要用有输入参数,有返回值的委托,那么Func委托 ...
- 委托delegate 泛型委托action<> 返回值泛型委托Func<> 匿名方法 lambda表达式 的理解
1.使用简单委托 namespace 简单委托 { class Program { //委托方法签名 delegate void MyBookDel(int a); //定义委托 static MyB ...
- 对委托 以及 action func 匿名函数 以及 lambda表达式的简单记录
class Program { public delegate void MyDelegate(string str); static void Main(string[] args) { // My ...
- C# 委托应用总结(委托,Delegate,Action,Func,predicate)
C# 委托应用总结 一.什么是委托 1.1官方解释 委托是一种定义方法签名的类型.当实例化委托时,您可以将其实例与任何具有兼容签名的方法相关联.您可以通过委托实例调用方法. 1.2个人理解 委托就是执 ...
- 浅谈C#中常见的委托<Func,Action,Predicate>(转)
一提到委托,浮现在我们脑海中的大概是听的最多的就是类似C++的函数指针吧,呵呵,至少我的第一个反应是这样的. 关于委托的定义和使用,已经有诸多的人讲解过,并且讲解细致入微,尤其是张子阳的那一篇.我就不 ...
随机推荐
- junit4X系列源码--总体介绍
原文出处:http://www.cnblogs.com/caoyuanzhanlang/p/3530267.html.感谢作者的无私分享. Junit是一个可编写重复测试的简单框架,是基于Xunit架 ...
- Python杂项
一. Python执行系统命令 Python可以使用system和popen来执行系统命令,使用时需要import os, 传入的参数都为一个字符创,不过这两者之间有些差异. os.system(cm ...
- java 多维数组遍历
java 多维数组遍历的顺序的性能问题 ps:下图为java多维数组内存分布原理.出自:http://math.hws.edu/javanotes/c7/two-dimensional-array.p ...
- 关于Scanner类
Scanner类 1.常用的两个方法: public int nextInt():获取一个int类型的值 public String nextLine():获取一个St ...
- 一步一步从原理跟我学邮件收取及发送 10.四句代码说清base64
经过前几篇的文章,大家应该都能预感到一定要讲解 base64 函数的内容了.是的,马上要到程序登录的代码,base64 是必须要实现的. base64 很早以前我就接触了,在项目中也很喜欢用.但每换一 ...
- c# 颜色RGB到HSB互相转换
/// <summary> /// 色相,饱和度,亮度转换成rgb值 /// </summary> /// <returns></returns> pu ...
- 给file_get_contents函数设置超时时间
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) ); $context = str ...
- eclipse open call hierarchy无效
问题: Eclipse中选中一个方法,右击选中open call hierarchy,不显示哪些地方调用了这个方法,却显示了这个方法里面调用了那些方法.前阵子还是好的,现在不知道为什么了. 解决: s ...
- js中定义对象的几种方式
转载:http://blog.sina.com.cn/s/blog_60f632050100wz7h.html (1)基于已有对象的扩充方法:适用于临时构建对象,弊端:每次构建对象都要新建一个. va ...
- BZOJ 1951: [Sdoi2010]古代猪文 [Lucas定理 中国剩余定理]
1951: [Sdoi2010]古代猪文 Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 2194 Solved: 919[Submit][Status] ...