Lambda variable scope

孤者浪人 提交于 2020-01-24 03:18:40

问题


Example:

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

var s = "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?


回答1:


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# 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.

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



来源:https://stackoverflow.com/questions/3133680/lambda-variable-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!