C# Lambda 表达式帮助
如果我使用如下所示的 lambda 表达式,
// assume sch_id is a property of the entity Schedules
public void GetRecord(int id)
{
_myentity.Schedules.Where(x => x.sch_id == id));
}
我假设(尽管未经测试)我可以使用匿名内联函数重写它,使用类似
_jve.Schedules.Where(delegate(Models.Schedules x) { return x.sch_id == id; });
我的问题是,我将如何在普通(非内联)函数中重写它,并且还是传入id参数。
If I use a lambda expression like the following
// assume sch_id is a property of the entity Schedules
public void GetRecord(int id)
{
_myentity.Schedules.Where(x => x.sch_id == id));
}
I'm assuming (although non-tested) I can rewrite that using an anonymous inline function using something like
_jve.Schedules.Where(delegate(Models.Schedules x) { return x.sch_id == id; });
My question is, how would I rewrite that in a normal (non-inline) function and still pass in the id parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简而言之,你不能将其作为一个独立的函数。在您的示例中,
id
实际上保存在闭包中。长的答案是,您可以编写一个捕获状态的类,方法是使用要操作的 id 值进行初始化,并将其存储为成员变量。在内部,闭包的操作类似 - 区别在于它们实际上捕获对变量的引用而不是它的副本。这意味着闭包可以“看到”它们所绑定的变量的更改。有关详细信息,请参阅上面的链接。
因此,例如:
The short answer is that you can't make it a stand-along function. In your example,
id
is actually preserved in a closure.The long answer, is that you can write a class that captures state by initializing it with the
id
value you want to operate against, storing it as a member variable. Internally, closures operate similarly - the difference being that they actually capture a reference to the variable not a copy of it. That means that closures can "see" changes to variables they are bound to. See the link above for more details on this.So, for example:
如果您只想将委托的主体放在其他地方,您可以使用此实现
If you only want to place the body of the delegate somewhere else you can achieve using this
您需要将 ID 保存在某处。这是由 使用闭包,这基本上就像使用值和方法创建一个单独的临时类。
You would need to save the ID somewhere. This is done for you by using a closure, which basically is like creating a separate, temporary class with the value and the method.