不能使用拉姆达前pressions ref或out参数 [英] Cannot use ref or out parameter in lambda expressions

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

问题描述

为什么不能使用的lambda前pression ref或out参数?

我遇到错误走到今天,发现一个解决方法,但我仍然好奇,为什么这是一个编译时错误。

下面是一个简单的例子:

 私人无效美孚()
    {
        int值;
        酒吧(满分值);
    }    私人无效栏(出int值)
    {
        值= 3;
        INT []数组= {1,2,3,4,5};
        INT为newValue = array.Where(一个=>一种==值)。首先();
    }


解决方案

Lambda表达式有改变,他们捕捉变量一生的外观。例如以下的λ前pression导致参数P1到的的不是作为后方法帧是不再在堆栈上其值可被访问的当前方法帧更长

  Func键< INT>示例(INT P1){
  回报()= GT; P1;
}

捕获变量的另一个特性是变化的变量也拉姆达前pression外部可见。例如下列打印42

 无效例2(INT P1){
  行动德尔=()=> {P1 = 42; }
  德尔();
  Console.WriteLine(P1);
}

这两个属性产生一定的效果集其飞ref参数的脸在以下方面


  • ref参数可能有固定的寿命。考虑通过一个局部变量作为ref参数的函数。

  • 在拉姆达副作用将需要对裁判参数本身可见。两个方法中,并在调用者。

这些是有些不相容的属性,并且是它们在拉姆达前pressions禁止的原因之一。

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.

Here's a simple example:

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

解决方案

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

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

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

  • ref parameters may have a fixed lifetime. Consider passing a local variable as a ref parameter to a function.
  • Side effects in the lambda would need to be visible on the ref parameter itself. Both within the method and in the caller.

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

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

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