简体   繁体   English

公司使用C#中的Func和Action代理吗?

[英]Are Func and Action Delegates in C# used by companies?

I really wonder if the Func and Action delegates are used by developing companies. 我真的很想知道Func和Action代表是否被开发公司使用。 And do they use it for events? 他们是否将它用于活动? I know it's a strange question but I already asked it to my teacher and many other people but nobody could give me an answer. 我知道这是一个奇怪的问题,但我已经向老师和其他许多人询问过,但没有人能给我一个答案。

In C#, Action and Func are extremely useful tools for reducing duplication in code and decreasing coupling. 在C#中, ActionFunc是减少代码重复和减少耦合的极其有用的工具。 And reduce duplication and make code reusable is important to any company 减少重复并使代码可重用对任何公司都很重要

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. 将Action和Func添加到工具箱是改进C#代码的一个非常重要的步骤。

As great exmaple of Using them : Linq is based on Action and Func and Predicate 作为使用它们的最佳例子: Linq基于ActionFuncPredicate

Here's an example of the power of these constructs, which illustrates for me the emptiness of the "junior devs might not understand it" argument. 这是这些结构的力量的一个例子,它向我展示了“初级开发者可能不理解它”的空虚论点。

If you have an Organisation class, which contains a collection of Department objects, and if the Department class contains a collection of Employee objects, how do you get the full set of employees for an organisation? 如果您有一个包含Department对象集合的Organisation类,并且Department类包含Employee对象的集合,那么如何获得组织的全部员工?

You could loop through the objects and build up a collection: 您可以遍历对象并构建集合:

var allEmployees = new List<Employee>();
foreach (var department in organisation.Departments)
{
    foreach (var employee in department.Employees)
    {
        allEmployees.Add(employee);
    }
}

or you could simply use the single statement 或者你可以简单地使用单一陈述

var allEmployees = organisation.Departments.SelectMany(d => d.Employees).ToArray();

This code is terser, and less susceptible to human error, than the manual loop, and the immutability of the resultant array is less prone to bugs than the mutable list. 与手动循环相比,此代码更简洁,并且不易受人为错误的影响,并且结果数组的不变性比可变列表更不容易出错。 To obtain these benefits, it is necessary to be comfortable with the use of lambdas to represent Func and Action constructs. 为了获得这些好处,有必要熟悉使用lambdas来表示FuncAction结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM