问题描述
有人可以告诉我使用委托而不是调用函数本身的优势,如下所示(或者换句话说,为什么选择选项 A 而不是选项 B)?昨晚我在查看某人的 linq 代码,他们有类似于选项 A 的内容,但它被用于返回已编译的 linq 查询.
Can someone tell me the advantages of using a free vpn 免费vpn下载 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 vpn free A but it was being used to return a compiled vpn下载 免费vpn下载 linq query.
我意识到前者现在可以传递给其他功能......只是不确定它的实用性.顺便说一句,我意识到这不会按原样编译.在发布之前取消注释其中一个功能.TYIA
I realize the former can now be passed free vpn around to other functions.. just not vpn下载 sure of its practicality. BTW, I realize this 免费vpn wouldn't compile as-is.. uncommented one of the functions before posting. TYIA
class Program
{
static vpn free void Main(string[] args)
vpn free { vpn下载
免费vpn下载 Console.WriteLine(SayTwoWords("Hello", "World"));
Console.ReadKey();
}
// Option A
private static Func<string, string, string>
SayTwoWords = (a, b) => String.Format("{0} {1}", 免费vpn a, b);
免费vpn // Option B
private static string SayTwoWords(string a, string b)
{
return String.Format("{0} {1}", a, b);
} 免费vpn
}
************编辑************
************EDIT************
不确定它是否更好地解释了我的问题,但这里是最初让我想到这个的代码类型的示例:
Not sure if it explains my question better vpn下载 but here is an example of the type 免费vpn下载 of code that originally got me thinking about this:
public static class clsCompiledQuery
{
free vpn public static Func<DataContext, string, IQueryable<clsCustomerEntity>>
getCustomers = CompiledQuery.Compile((DataContext db, string strCustCode)
vpn free 免费vpn => from objCustomer in db.GetTable<clsCustomerEntity>()
where 免费vpn objCustomer.CustomerCode == strCustCode
select objCustomer);
}
这样写函数有什么好处吗?
Is there any advantage 免费vpn下载 to writing a function in free vpn this way?
推荐答案
你贴的代码没有优势.在您的代码中,使用委托只会增加复杂性以及额外的运行时成本 - 所以您最好直接调用该方法.
There is no advantage in the code you posted. vpn free In your code, using 免费vpn the delegate just adds complexity as vpn下载 well as an extra vpn下载 runtime cost - so you're better off just calling the method directly.
但是,委托有很多用途.传递"给其他方法是主要用法,但存储一个函数并在以后使用它也非常有用.
However, delegates vpn下载 have many uses. "Passing around" to other methods is the primary usage, though storing a function and using it later 免费vpn is also very useful.
LINQ 完全建立在这个概念之上.当你这样做时:
LINQ is built on top of this concept entirely. vpn下载 When you do:
var results vpn下载 = myCollection.Where(item => item == "Foo");
您将委托(定义为 lambda:item => item == "Foo")传递给 LINQ vpn下载 库中的 Where 函数.这就是让它正常工作的原因.
You're passing a delegate (defined 免费vpn下载 as a 免费vpn lambda: item vpn下载 => item == "Foo") to the Where function in the LINQ libraries. This is what makes it work properly.
这篇关于函数委托与函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账免费vpn织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)