问题描述
有人可以告诉我使用委托而不是调用函数本身的优势,如下所示(或者换句话说,为什么选择选项 A 而不是选项 B)?昨晚我在查看某人的 linq 代码,他们有类似于选项 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************
不确定它是否更好地解释了我的问题,但这里是最初让我想到这个的代码类型的示例:
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?
推荐答案
你贴的代码没有优势.在您的代码中,使用委托只会增加复杂性以及额外的运行时成本 - 所以您最好直接调用该方法.
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:item => item == "Foo"
)传递给 LINQ 库中的 Where
函数.这就是让它正常工作的原因.
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.
这篇关于函数委托与函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!