如何“传出”参数传入 lambda 表达式
我有一个具有以下签名的方法:
private PropertyInfo getPropertyForDBField(string dbField, out string prettyName)
在其中,我根据给定的 dbField
找到关联的值 prettyName
。然后,我想查找名称为 prettyName
的所有属性(如果有),因此我尝试执行以下操作:
IEnumerable<PropertyInfo> matchingProperties =
getLocalProperties().Where(prop =>
prop.Name.Equals(prettyName)
);
但是,这会出现以下错误:
不能在匿名方法、lambda 表达式或查询表达式中使用 ref 或 out 参数“prettyName”
在我尝试在 Where
prettyName 的方法中> lambda 参数,prettyName
肯定已初始化。如果 prettyName
无法初始化为有效值,我返回
。我可以在这里做一些技巧让我在 lambda 表达式中使用 prettyName
吗?
编辑:如果重要的话,我正在使用.NET 3.5。
I have a method with the following signature:
private PropertyInfo getPropertyForDBField(string dbField, out string prettyName)
In it, I find the associated value prettyName
based on the given dbField
. I then want to find all properties, if any, that have the name prettyName
, so I'm trying to do the following:
IEnumerable<PropertyInfo> matchingProperties =
getLocalProperties().Where(prop =>
prop.Name.Equals(prettyName)
);
However, this gives the following error:
Cannot use ref or out parameter 'prettyName' inside an anonymous method, lambda expression, or query expression
By the point in the method where I'm trying to use prettyName
in the Where
lambda parameter, prettyName
is definitely initialized. I return
if prettyName
cannot be initialized to a valid value. Is there some trick I could do here to let me use prettyName
in the lambda expression?
Edit: I'm using .NET 3.5 if it matters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是为了澄清。可以在 lambda 中使用被调用方法的 ref/out 参数。
如果指定参数的类型,还可以使用 ref 或 out。这意味着将 PrettyName 作为参数发送给 lambda。
Where 子句仅接受一个参数,即列表中的属性元素。这就是阻止您向 lambda 添加参数的原因。
不想给人们留下不能在 lambda 中使用这些参数的错误印象。你只是不能通过捕获来使用它们。
Just to clarify. It's possible to use ref/out arguments from a called method in a lambda.
You can also use a ref or out if you specify type of the parameter. Which means sending prettyName as a parameter to the lambda.
Where clause takes in only one argument, which is the property element in the list. This is what prevents you from adding an argument to the lambda.
Didn't want to leave people the false impression that you cannot use these arguments in a lambda. You just can't use them by capture.
正如编译器错误所示,不允许在 lambda 表达式内使用 out 或 ref 参数。
为什么不直接使用副本呢?无论如何,lambda 都不想改变变量,所以我没有看到任何缺点。
或者,您可以使用局部变量(以评估适当的名称等),并在从方法返回之前分配
out
参数prettyName
。如果方法内没有明显的分支,这可能会更具可读性。As the compiler error indicates, it isn't allowed to use out or ref parameters inside lambda expressions.
Why not just use a copy? It's not like the lambda wants to mutate the variable anyway, so I don't see a downside.
Alternatively, you can use a local throughout (to evaluate the appropriate name etc.), and assign the
out
parameterprettyName
just before returning from the method. This will probably be more readable if there isn't significant branching within the method.