FUNC代表VS功能 [英] Func Delegate vs Function

查看:159
本文介绍了FUNC代表VS功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我使用委托的优点,而不是调用函数本身,如下图所示(或者换句话说,为什么在选项B中选择选项A)?我看着别人的LINQ code,昨晚,他们有相似的选项A的东西,但它被用来返回编译LINQ查询。

Can someone tell me the advantages of using a delegate as opposed to calling the function itself as shown below (or in other words why choose Option A over Option B)? I was looking at someone's linq code last night and they had something similar to Option A but it was being used to return a compiled linq query.

我知道前者现在可以通过周围的其他功能..只是不知道它的实用性。顺便说一句,我知道这不会编译原样..功能注释掉一篇帖子之前。 TYIA

I realize the former can now be passed around to other functions.. just not sure of its practicality. BTW, I realize this wouldn't compile as-is.. uncommented one of the functions before posting. TYIA

class Program
{
    static void Main(string[] args)
    {   
        Console.WriteLine(SayTwoWords("Hello", "World"));
        Console.ReadKey();
    }

    // Option A
    private static Func<string, string, string>
        SayTwoWords = (a, b) => String.Format("{0} {1}", a, b);

    // Option B
    private static string SayTwoWords(string a, string b)
    {
        return String.Format("{0} {1}", a, b);
    }        
}

的**的 * 修改 * 的****

***EDIT*****

不知道这是否说明我的问题更好,但这里是code类型的一个例子,最初让我思考一下:

Not sure if it explains my question better but here is an example of the type of code that originally got me thinking about this:

public static class clsCompiledQuery
{
    public static Func<DataContext, string, IQueryable<clsCustomerEntity>>
        getCustomers = CompiledQuery.Compile((DataContext db, string strCustCode)
            => from objCustomer in db.GetTable<clsCustomerEntity>()
            where objCustomer.CustomerCode == strCustCode
            select objCustomer);
}

它有什么优势以这种方式写一个函数?

Is there any advantage to writing a function in this way?

推荐答案

有没有优势,在code您发布。在您的code,使用委托只是增加了复杂性以及额外的成本运行时间 - 所以你最好只需要直接调用方法

There is no advantage in the code you posted. In your code, using the delegate just adds complexity as well as an extra runtime cost - so you're better off just calling the method directly.

不过,代表们有很多用途。 传递至其它方法是主要的使用,虽然存储的函数,并使用它以后也是非常有用的。

However, delegates have many uses. "Passing around" to other methods is the primary usage, though storing a function and using it later is also very useful.

LINQ是建立在这个概念完全的顶部。当你这样做:

LINQ is built on top of this concept entirely. When you do:

var results = myCollection.Where(item => item == "Foo");

您正在传递一个委托(定义为一个lambda:项目=&GT;项目==富)的其中,中的LINQ库函数。这是什么使得它正常工作。

You're passing a delegate (defined as a lambda: item => item == "Foo") to the Where function in the LINQ libraries. This is what makes it work properly.

这篇关于FUNC代表VS功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆