Func委托与功能

Bre*_*wha 12 c# delegates

有人可以告诉我使用委托的优势而不是如下所示调用函数本身(或者换句话说为什么选择选项A而不是选项B)?我昨晚看了某人的linq代码,他们有类似于Option A的东西,但它被用来返回编译的linq查询.

我意识到前者现在可以传递给其他功能......只是不确定它的实用性.顺便说一句,我意识到这不会按原样编译..在发布之前取消注释其中一个功能.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);
    }        
}
Run Code Online (Sandbox Code Playgroud)

************编辑************

不确定它是否更好地解释了我的问题,但这里是一个最初让我思考这个问题的代码类型的例子:

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);
}
Run Code Online (Sandbox Code Playgroud)

以这种方式编写函数有什么好处吗?

Ree*_*sey 13

您发布的代码没有任何优势.在您的代码中,使用委托只会增加复杂性以及额外的运行时成本 - 因此您最好直接调用该方法.

但是,代表们有很多用途."传递"到其他方法是主要用法,尽管存储函数并在以后使用它也非常有用.

LINQ完全基于这个概念.当你这样做时:

var results = myCollection.Where(item => item == "Foo");
Run Code Online (Sandbox Code Playgroud)

你传递一个委托(定义为拉姆达:item => item == "Foo")将Where在LINQ库函数.这是使它正常工作的原因.