【发布时间】:2013-06-29 21:55:32
【问题描述】:
有人能告诉我使用委托而不是调用函数本身的优势,如下所示(或者换句话说,为什么选择选项 A 而不是选项 B)?昨晚我在查看某人的 linq 代码,他们有类似于选项 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);
}
}
************编辑************
不确定它是否更好地解释了我的问题,但这里是最初让我想到这个的代码类型的示例:
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);
}
这样写函数有什么好处吗?
【问题讨论】: