EXPLAINING WHAT ACTION AND FUNC ARE
http://simpleprogrammer.com/2010/09/24/explaining-what-action-and-func-are/
Explaining What Action And Func Are
In C#, Action and Func are extremely useful tools for reducing duplication in code and decreasing coupling.
It is a shame that many developers shy away from them because they don’t really understand them.
Adding Action and Func to your toolbox is a very important step in improving your C# code.
It’s not really that hard to understand what they do and how to use them, it just takes a little patience…
A simple way of thinking about Action<>
Most of us are pretty familiar with finding sections of repeated code, pulling that code out into a method and making that method take parameters to represent the differences.
Here is a small example, which should look pretty familiar:
public void SteamGreenBeans(){ var greenBeans = new GreenBeans(); Clean(greenBeans); Steam(greenBeans, Minutes.Is(10)); Serve(greenBeans);}public void SteamCorn(){ var corn = new Corn(); Clean(corn); Steam(corn, Minutes.Is(15)); Serve(corn);}public void SteamSpinach(){ var spinach = new Spinach(); Clean(spinach); SteamVegetable(spinach, Minutes.Is(8)); Serve(spinach);} |
Each one of these methods pretty much does the same thing. The only difference here is the type of vegetable and the time to steam it.
It is a simple and common refactor to refactor that code to:
public void SteamGreenBeans(){ SteamVegetable(new GreenBeans(), 10);}public void SteamCorn(){ SteamVegetable(new Corn(), 15);}public void SteamSpinach(){ SteamVegetable(new Spinach(), 8);}public void SteamVegetable(Vegetable vegetable, int timeInMinutes){ Clean(vegetable); Steam(vegetable, Minutes.Is(timeInMinutes)); Serve(vegetable);} |
Much better, now we aren’t repeating the “actions” in 3 different methods.
Now let’s imagine we want to do something more than steam. We need to be able to fry or bake the vegetables. How can we do that?
Probably we will have to add some new methods for doing that. So we will end up with something like this:
public void SteamVegetable(Vegetable vegetable, int timeInMinutes){ Clean(vegetable); Steam(vegetable, Minutes.Is(timeInMinutes)); Serve(vegetable);}public void FryVegetable(Vegetable vegetable, int timeInMinutes){ Clean(vegetable); Fry(vegetable, Minutes.Is(timeInMinutes)); Serve(vegetable);}public void BakeVegetable(Vegetable vegetable, int timeInMinutes){ Clean(vegetable); Bake(vegetable, Minutes.Is(timeInMinutes)); Serve(vegetable);} |
Hmm, lots of duplication again. No problem. Let’s just do what we did to the first set of methods and make a CookVegetable method. Since we always clean, then cook, then serve, we should be able to just pass in the method of cooking we will use.
Oh wait, how do we do that? We can’t just extract out Bake or Fry or Steam, because the Bake, Fry and Steam methods are logic and not data.
Unless… unless we can make them data. Can we do that?
We sure can, check this out:
public void SteamVegetable(Vegetable vegetable, int timeInMinutes){ CookVegetable(vegetable, Steam, timeInMinutes);}public void FryVegetable(Vegetable vegetable, int timeInMinutes){ CookVegetable(vegetable, Fry, timeInMinutes);}public void BakeVegetable(Vegetable vegetable, int timeInMinutes){ CookVegetable(vegetable, Bake, timeInMinutes);}public void CookVegetable(Vegetable vegetable, Action<Vegetable, int> cookingAction, int timeInMinutes){ Clean(vegetable); cookingAction(vegetable, Minutes.Is(timeInMinutes)); Serve(vegetable);} |
We got rid of the duplicated code the same way we did when we did our first refactor, except this time we parameterized method calls instead of data.
If you understood this, you understand Action. Action is just a way of treating methods like they are data. Now you can extract all of the common logic into a method and pass in data that changes as well as actions that change.
Congratulations, you are doing the strategy pattern without having to create an abstract base class and a huge inheritance tree!
So when you see Action, just think “ah, that means I am passing a method as data.”
It really is as simple as that.
Action<Vegetable, CookingTime> translated to English is: “A method that takes a Vegetable and a CookingTime as parameters and returns void.”
What about Func<>?
If you understand Action, you understand Func.
Func<X, Y, Z> translated to English is: “A method that takes an X, and a Y as parameters and returns a Z”.”
The only difference between Action and Func is that Func’s last template parameter is the return type. Funcs have non-void return values.
Bonus: Predicate is a Func that always returns a boolean.
That’s all there is to it. There really isn’t a need to know much more than that to make sure of Action and Func in order to start using them.
Further Resources for Action and Func
If you are interested in some other ways to apply Action and Func, here are some posts I have written which focus on them.
- Pulling out the Switch: It’s Time for a Whooping
- Parsing Columns Like a Ninja
- The Power of Func<>
- Super Combo: Map + Function Pointer
EXPLAINING WHAT ACTION AND FUNC ARE的更多相关文章
- Delegate、Predicate、Action和Func
写在前面 Delegate Predicate Action Func 逆变和协变 先说下什么是委托(Delegate),委托在C#中是一种类型,和Class是一个级别,但是我们经常把它看做是一个方法 ...
- VS2012 Unit Test(Void, Action, Func) —— 对无返回值、使用Action或Func作为参数、多重载的方法进行单元测试
[提示] 1. 阅读文本前希望您具备如下知识:了解单元测试,了解Dynamic,熟悉泛型(协变与逆变)和Lambda,熟悉.NET Framework提供的 Action与Func委托.2.如果您对单 ...
- C#系统委托之Action And Func
Action Action<T> Func Func<T> Action:封装一个方法,该方法不具有参数并且不返回值 public delegate void Action() ...
- Action<>和Func<> 委托【代理】
C#中的Action<>和Func<> 其实他们两个都是委托[代理]的简写形式. 一.[action<>]指定那些只有输入参数,没有返回值的委托 Delegate的 ...
- .NET中的Action及Func泛型委托
委托,在C#编程中占有极其重要的地位,委托可以将函数封装到委托对象中,并且多个委托可以合并为一个委托,委托对象则可以像普通对象一样被存储.传递,之后在任何时刻进行调用,因此,C#中函数回调机制的实现基 ...
- C#高级功能(三)Action、Func,Tuple
Action和Func泛型委托实际上就是一个.NET Framework预定义的委托,3.5引入的特性.基本涵盖了所有常用的委托,所以一般不用用户重新声明. Action系列泛型委托,是没有返回参数的 ...
- 使用.NET中的Action及Func泛型委托
委托,在C#编程中占有极其重要的地位,委托可以将函数封装到委托对象中,并且多个委托可以合并为一个委托,委托对象则可以像普通对象一样被存储.传递,之后在任何时刻进行调用,因此,C#中函数回调 ...
- Action 和 Func
C# 中的两个动态委托类型 也就是说我们不用在使用委托的时候就去声明一个委托对象,而是通过Action和Func就可以模拟出我们自己要用到的委托 区别: Action 表示没有返回值的委托 例如:A ...
- 委托学习续:Action、Func和Predicate
我们先看一个上一章的委托的例子: using System; using System.Collections.Generic; using System.Linq; using System.Tex ...
随机推荐
- x01.Weiqi.10: 死活问题
估计得不错,点目后,仅一个方法:UpdateMeshes5() 就完美解决了梅花六.刀把五.斗笠四.盘角曲四等死活问题.先来看看效果图: 其代码如下: void UpdateMeshes5(bool ...
- C++的友元类和友元函数实例
#include <math.h> #include<iostream> using namespace std; class Point { public: Point(do ...
- poj1006 / hdu1370 Biorhythms (中国剩余定理)
Biorhythms 题意:读入p,e,i,d 4个整数,已知(n+d)%23=p; (n+d)%28=e; (n+d)%33=i ,求n . (题在文末) 知识点:中国剩余定理 ...
- ZBrush该如何通过结合KeyShot制作逼真玉佩
玉在中国的文明史上有着特殊的地位,古人的很多生活器具都是玉雕成的,能常戴在身上的惟有玉佩,古语有云"君子无故,玉不去身".即便到了现代,仍有很多人佩戴玉,倒不一定是因为它有多彰显地 ...
- UITabBarController的创建与自定义TarBar---学习笔记三
代码如下: #import <UIKit/UIKit.h> @interface BSJTabBarViewController : UITabBarController @end #im ...
- Oracle日期格式转换,tochar(),todate()
Oracle日期格式转换 本文主要介绍Oracle中的日期转换. 1. 日期转化为字符串 (以2016年10月20日为例) select to_char(sysdate,'yyyy-mm-dd hh2 ...
- Java8并发教程:Threads和Executors
来之:ImportNew 欢迎阅读我的Java8并发教程的第一部分.这份指南将会以简单易懂的代码示例来教给你如何在Java8中进行并发编程.这是一系列教程中的第一部分.在接下来的15分钟,你将会学会如 ...
- ThreadLocal实现方式&使用介绍—无锁化线程封闭
原文出处: xieyu_zy 虽然现在可以说很多程序员会用ThreadLocal,但是我相信大多数程序员还不知道ThreadLocal,而使用ThreadLocal的程序员大多只是知道其然而不知其所以 ...
- iOS Run_time
Runtime是想要做好iOS开发,或者说是真正的深刻的掌握OC这门语言所必需理解的东西.最近在学习Runtime,有自己的一些心得,整理如下,一为 查阅方便二为 或许能给他人一些启发,三为 希望得到 ...
- C++与C# UDP通信实例(同一台PC)
对于同一个PC机而言,服务器端和客户端在一个PC机上面,端口必须要不一样,不然会冲突. 你总不能自己又当爹又当妈吧. 所以在进行程序设计的时候,需要考虑这一点: 在此接口设计中,C++当作UDP的服务 ...