本文介绍了Lambda变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

myObject.Stub(s => s.MyMethod(null)).IgnoreArguments().Return("bleh");

var s = "s";

在同一方法中,lambda中定义了一个变量"s",另一个变量"s"被定义为局部变量.当我将鼠标悬停在第一个"s"上时,Visual Studio会告诉我在下面定义了一个有冲突的变量".为什么这些冲突?在lambda中的"s"肯定不能在其括弧内使用吗?

A variable "s" is defined in a lambda and another variable "s" as a local variable within the same method. Visual Studio tells me "A conflicting variable is defined below" when I hover over the first "s". Why are these conflicting; the "s" in the lambda is not available outside of its enclosing brackets surely?

推荐答案

它们之所以冲突,是因为C#的规则是具有相同简单名称的任何两种用法不能用于指代两个不同的事物在块内立即将它们中的任何一个封闭起来.在您的示例中,简单名称"s"用于表示包含局部变量声明的块内的两件事:它表示局部变量和lambda参数. 是非法的.我注意到您收到的错误消息告诉您:

They are conflicting because a rule of C# is that any two uses of the same simple name cannot be used to refer to two different things inside the block immediately enclosing either of them. In your example the simple name "s" is used to mean two things inside the block enclosing the local variable declaration: it means a local variable, and a lambda parameter. That is what is illegal. I note that the error message you get tells you this:


A local variable named 's' cannot be declared in this scope because it
would give a different meaning to 's', which is already used in a
'child' scope to denote something else

C#不允许在同一块中使用相同的简单名称来表示两件事,因为这样做会使代码易于出错,难以编辑,难以阅读,难以重构以及难以调试.最好不要允许这种不良的编程习惯,而不要允许它并冒造成错误的风险,因为您认为"s"在整个块中的含义相同.

C# does not allow you to have the same simple name mean two things in the same block because doing so makes code error prone, hard to edit, hard to read, hard to refactor, and hard to debug. It is better to disallow this bad programming practice than to allow it and risk you causing bugs because you assumed that "s" means the same thing throughout the block.

当代码只有两行时,很容易记住s有两种不同的含义,但是当它有数百行时,就不那么容易了.

When the code is only two lines long it is easy to remember that there are two different meanings for s, but when it is hundreds of lines long, not so easy.

有关此规则的更多信息,请参见:

For more information about this rule, see:

http://blogs.msdn.com/b/ericlippert/archive/2009/11/02/simple-names-are-not-so-simple.aspx

这篇关于Lambda变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:37