.NET Func and Action Delegates

.NET Func and Action Delegates

by Richard Carr, published at http://www.blackwasp.co.uk/FuncAction.aspx

The Func and Action generic delegates were introduced in the .NET framework version 3.5. They provide flexible delegates with generic parameters that can be used for many purposes, including passing lambda expressions to method parameters.


Generic Delegates

The .NET framework version 3.5 introduced two new sets of generic, parameterised delegatesnamed Func and Action. The Func delegate can be used to encapsulate a method that accepts between zero and four arguments and returns a value. The Action delegate also represents methods with zero to four parameters but differs from Func in that the method must return void.

The new delegates can be used to reduce the number of delegates that you define explicitly. In situations where you would need a delegate that matches one of the predefined Func or Action signatures, you may decide to use the built-in version. You should consider the naming of the delegate however, as "Func" or "Action" may not express your intent as clearly as another name.

One of the key reasons for the introduction of Func and Action is their relationship withlambda expressions. Every lambda expression's underlying type is one of these generic delegates. This means that lambda expressions can be passed to method parameters of the appropriate type without explicitly creating a delegate. Many of the LINQ standard query operators accept Func arguments to take advantage of this feature.

Func Delegate

There are five variations upon the Func delegate, each allowing a different number of parameters to be represented. In each case, the return value and the parameters are defined as generic types, allowing the types to vary according to the method that the delegate encapsulates. The five signatures are shown below. Note that the return value of the method is always the last element in the list of types.

publicdelegateTResult Func<TResult>()

publicdelegateTResult Func<T, TResult>(T arg)

publicdelegateTResult Func<T1, T2, TResult>(T1 arg1, T2 arg2)

publicdelegateTResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3)

publicdelegateTResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Using Func<TResult>

The most basic variant of Func is Func<TResult>. This delegate represents methods that return a value but have no parameters. We can demonstrate this with the following sample code. In the example, a new delegate is created using an anonymous method. The method returns a double-precision floating-point number containing a tax rate value.

Func<double> taxRate =delegate{return17.5; };

Console.WriteLine("{0}%", taxRate());  // Outputs "17.5%"

We can create the same functionality using a lambda expression. Any lambda that accepts no arguments and returns a double is of the type Func<double>. To demonstrate, try executing the following:

Func<double> taxRate = () => 17.5;

Console.WriteLine("{0}%", taxRate());  // Outputs "17.5%"

Using Func with Parameters

Func can represent methods with up to four parameters. In the next example a Func delegate is used to reference an anonymous method that accepts three integer arguments and returns a long integer.

Func<int, int,int,long> multiply =delegate(inta,intb,intc) {returna * b * c; };

Console.WriteLine(multiply(2, 3, 4));   // Outputs "24"

Again, the code can be recreated using a lambda expression in place of the anonymous method. In this case, the three parameters are named a, b and c. The parameter types do not need to be included in the lambda expression as they, and the return type, are inferred by the compiler.

Func<int, int,int,long> multiply = (a, b, c) => a * b * c;

Console.WriteLine(multiply(2, 3, 4));   // Outputs "24"

Action Delegate

As with Func, the Action delegate has five variations. These allow the encapsulation of methods that have up to four parameters but do not return a value. Again, all of the parameters are generic types allowing any type to be used for each argument. The five signatures are as follows:

publicdelegatevoidAction()

publicdelegatevoidAction<T, >(T arg)

publicdelegatevoidAction<T1, T2>(T1 arg1, T2 arg2)

publicdelegatevoidAction<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)

publicdelegatevoidAction<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Using Action

The simplest Action delegate is used with methods that accept no parameters and return no values. The following code demonstrates this with an anonymous method that outputs text to the console.

Action showMessage = delegate{ Console.WriteLine("Hello, world"); };

showMessage();                  // Outputs "Hello, world"

As with the Func delegates, Action can be used with lambda expressions. The equivalent of the previous example can be created using a statement lambda, as follows:

Action showMessage = () => { Console.WriteLine("Hello, world"); };

showMessage();                  // Outputs "Hello, world"

Using Action with Parameters

As a final example of the basic use of Action, consider the following example. This code uses a single string parameter for the delegate. The parameter accepts a message to be outputted to the console.

Action<string> showMessage =delegate(stringmsg) { Console.WriteLine(msg); };

showMessage("Hello, world");   // Outputs "Hello, world"

This example can be recreated using a statement lambda that includes a parameter. In this case the string parameter's type is inferred.

Action<string> showMessage = (msg) => { Console.WriteLine(msg); };

showMessage("Hello, world");   // Outputs "Hello, world"

 

Using Generic Delegates as Parameter Types

The Func delegate is commonly used as the type for parameters of methods that accept lambda expressions. These include LINQ standard query operators and similar methods that you create in your own projects. We will demonstrate this with this article's final example.

The following method defines an array containing the names of ten fruits. The method returns a filtered list of these fruits based upon the delegate passed as the only argument. Note that the types assigned to the Func delegate specify that the encapsulated method must receive a single string parameter and return a Boolean value. We could execute the passed method against each fruit string in a for-each loop. However, for simplicity the example uses the "Where" query operator.

privatestaticstring[] Fruit(Func<string,bool> filter)

{

    string[] fruit =newstring[]

        { "Apple","Banana","Cherry","Damson","Elderberry","Fig","Grapefruit",

          "Huckleberry","Lemon","Mango"};

    returnfruit.Where(filter).ToArray();

}

To test the method, add the following code to the Main method of a console application. This code calls the Fruit method, applying a filter that returns only fruit with a name shorter than six characters. The fruit names are then outputted.

string[] shortFruit = Fruit(f => f.Length < 6);

foreach(stringfruitinshortFruit)

    Console.WriteLine(fruit);

 

/* OUTPUT

 

Apple

Fig

Lemon

Mango

 

*/

 



Python网络爬虫与推荐算法新闻推荐平台:网络爬虫:通过Python实现新浪新闻的爬取,可爬取新闻页面上的标题、文本、图片、视频链接(保留排版) 推荐算法:权重衰减+标签推荐+区域推荐+热点推荐.zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值