我已经快速阅读了Microsoft Lambda Expression文档.
这种例子帮助我更好地理解了:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
Run Code Online (Sandbox Code Playgroud)
不过,我不明白为什么会有这样的创新.它只是一种在"方法变量"结束时死亡的方法,对吗?为什么我应该使用它而不是真正的方法?
有人可以告诉我使用委托的优势而不是如下所示调用函数本身(或者换句话说为什么选择选项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) 我是实体框架的新手,虽然我已经掌握了基础知识,但我对我不理解的特定语法感到磕磕绊绊.代码可以工作,但它对我来说有点"黑匣子",而且由于不了解它,我受到了一些阻碍.
我在我的类中声明了一个本地私有变量:
private clientexperienceEntities ceContext;
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我实例化它:
ceContext = new clientexperienceEntities();
Run Code Online (Sandbox Code Playgroud)
下一行是我遇到困难的部分:
var client = ceContext.clients.First(a => a.ID == _ID);
Run Code Online (Sandbox Code Playgroud)
具体来说,First方法的参数究竟a => a.ID == _ID意味着什么?我知道它正在告诉上下文根据值中包含的主键值找到第一个匹配记录_ID.但我不明白'a'来自哪里,或者我想用什么名字,'b'或'cat'.
这个语法是Linq的一部分吗?我甚至不确定究竟要搜索什么来理解它.
正如我所说的语句有效,我可以操纵返回的实体,但我只是不完全理解该参数构造.