C# - 如何传递“出”参数为lambda表达式 [英] C# - how to pass 'out' parameter into lambda expression

查看:1543
本文介绍了C# - 如何传递“出”参数为lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面签名的方法:

private PropertyInfo getPropertyForDBField(string dbField, out string prettyName)

在这,我找到关联的值 prettyName 根据给定 dbField 。然后,我想找到的所有属性,如果有的话,有名称 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:

不能使用匿名方法内ref或out参数prettyName,lambda表达式或查询表达式

Cannot use ref or out parameter 'prettyName' inside an anonymous method, lambda expression, or query expression

通过在方法的地步,我想在其中,拉姆达参数使用 prettyName prettyName 绝对是初始化。我收益如果 prettyName 不能被初始化为有效值。有一些诀窍,我可以在这里做的,让我在lambda表达式?

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?

修改使用 prettyName 我使用.NET 3.5,如果它的事项

I'm using .NET 3.5 if it matters.

推荐答案

由于编译器错误表明,它不是' ŧ允许使用out或ref参数的lambda表达式中。

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.

string prettyNameCopy = prettyName;
var matchingProperties = getLocalProperties()
                        .Where(prop => prop.Name == prettyNameCopy);



另外,你可以使用本地整个(评估适当的名称等),并分配退出参数 prettyName 刚刚从方法返回之前。这可能会更加可读,如果没有显著在方法中的分支

Alternatively, you can use a local throughout (to evaluate the appropriate name etc.), and assign the outparameter prettyName just before returning from the method. This will probably be more readable if there isn't significant branching within the method.

这篇关于C# - 如何传递“出”参数为lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆