不能在 lambda 表达式中使用 ref 或 out 参数 [英] Cannot use ref or out parameter in lambda expressions

查看:35
本文介绍了不能在 lambda 表达式中使用 ref 或 out 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能在 lambda 表达式中使用 ref 或 out 参数?

Why can't you use a ref or out parameter in a lambda expression?

我今天遇到了这个错误并找到了解决方法,但我仍然很好奇为什么这是一个编译时错误.

I came across the error today and found a workaround but I was still curious why this is a compile-time error.

CS1628:不能在 ref 或 out 参数中使用'匿名方法、lambda 表达式或查询表达式中的参数'

CS1628: Cannot use in ref or out parameter 'parameter' inside an anonymous method, lambda expression, or query expression

这是一个简单的例子:

private void Foo()
{
    int value;
    Bar(out value);
}

private void Bar(out int value)
{
    value = 3;
    int[] array = { 1, 2, 3, 4, 5 };
    int newValue = array.Where(a => a == value).First();
}

推荐答案

Lambda 的外观改变了它们捕获的变量的生命周期.例如,下面的 lambda 表达式导致参数 p1 存活 比当前方法帧长,因为它的值可以在方法帧不再在堆栈上之后访问

Lambdas have the appearance of changing the lifetime of variables that they capture. For instance the following lambda expression causes the parameter p1 to live longer than the current method frame as its value can be accessed after the method frame is no longer on the stack

Func<int> Example(int p1) {
  return () => p1;
}

被捕获变量的另一个特性是对变量的更改在 lambda 表达式之外也是可见的.例如下面打印 42

Another property of captured variables is that changes to the variable are also visible outside the lambda expression. For example the following prints 42

void Example2(int p1) {
  Action del = () => { p1 = 42; }
  del();
  Console.WriteLine(p1);
}

这两个属性产生了一组特定的效果,它们以下列方式面对 ref 参数

These two properties produce a certain set of effects which fly in the face of a ref parameter in the following ways

  • ref 参数可能有固定的生命周期.考虑将局部变量作为 ref 参数传递给函数.
  • lambda 中的副作用需要在 ref 参数本身上可见.在方法内和调用者中.

这些属性有些不兼容,这也是它们在 lambda 表达式中被禁止的原因之一.

These are somewhat incompatible properties and are one of the reasons they are disallowed in lambda expressions.

这篇关于不能在 lambda 表达式中使用 ref 或 out 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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