English 中文(简体)
为什么LINQ查询之外存在兰巴达变量范围?
原标题:Why Lambda variable scope exists outside LINQ Query?

我读了这个问题 (<< a href='"https://stackoverflow.com/ questions/10494074/ what - is -the -scope-f-a-lambda-可变-in-c-'?

但它是关于兰巴达变异范围 在LINQ查询。

现在回答我的问题<强/强>

假设我有一个很简单的LINQ查询

var Foo = FoobBar.Select(x => x);
var x = somefunction();

编译者说: A 本地变量 x 不能在此范围内声明, 因为它会赋予 x 不同的含义, 而 x 已经在子范围中用于表示其他

为什么如此? 当 LINQ 查询结束时, Lambda 变量应该停止存在吗?

EDIT: 在读完答复后,我得出结论认为,其外部 x (从功能返回),其范围在LINQ 查询范围内。

最佳回答

它与LINQ无关,它与儿童范围有关。

例如:

foreach (var bar in FooBar.Bars)
        {
            var x = FooBar.GetFoo();
        }
var x = new Foo();

从编译器中产生完全相同的错误消息 。

To fix that you just have to place variables in different (non-nesting) scopes. 例如:

foreach (var bar in FooBar.Bars)
        {
            var x = FooBar.GetBar();
        }
{
    var x = new Foo();
}
问题回答

让我们仔细看一看,

var Foo = FoobBar.Select(x => x);

表达式中 x 结尾的 x 真实范围

var x = somefunction()

现在,这很有趣, 这是用于同样使用 amda 表达式的整个方法的范围, 所以汇编者无法区分, 因为后者的范围与前者重叠。 并且非常信息化的信息太“ 强” 给 x 带来不同的含义, 已经在子范围 (在您的情况下选择) (在您的情况下选择)

它并不清楚(对编译者来说) 您指的是第二个 x (在 之后) 的哪个 x 。

如果你写了这个:

var Foo = FoobBar.Select(y => x);
var x = somefunction();

使羊羔中的 x 与某些功能结果相冲突。

无法在相同范围内声明同名的两个变量。

“同一范围”意指两者均在目前的范围之内。

void method()
{
    int a;
    int a; //wrong!
}

一个在当期,另一个在儿童范围。

void method()
{
    int a;
    for(;;)
    {
        int a; //wrong again!
    }
}

这是设计好的, 用于从 < code> int 到 ambda 引用的任何变量 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...