17

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.

4

2 回答 2

29

只是为了澄清。可以在 lambda 中使用来自被调用方法的 ref/out 参数。

如果指定参数的类型,也可以使用 ref 或 out。这意味着将 prettyName 作为参数发送给 lambda。

(prop, ref string prettyName) => prop.Name.Equals(prettyName);

Where 子句只接受一个参数,即列表中的属性元素。这就是阻止您向 lambda 添加参数的原因。

不想给人们留下无法在 lambda 中使用这些参数的错误印象。您只是不能通过捕获来使用它们。

于 2012-08-08T13:43:10.967 回答
20

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);

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.

于 2010-10-28T18:04:13.023 回答