variable scope in statement blocks

前端 未结 9 1832
梦如初夏
梦如初夏 2020-12-01 21:14
for (int i = 0; i < 10; i++)
{
    Foo();
}
int i = 10; // error, \'i\' already exists

----------------------------------------    

for (int i = 0; i < 10; i         


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 22:01

    Yea, I second the "nanny-state compilerism" comment. What's interesting is that this is ok.

    for (int i = 0; i < 10; i++)
    {
    
    }
    
    for (int i = 0; i < 10; i++)
    {
    
    }
    

    and this is ok

    for (int i = 0; i < 10; i++)
    {
    
    }
    
    for (int j = 0; j < 10; j++)
    {
        var i = 12;                
    }
    

    but this is not

    for (int i = 0; i < 10; i++)
    {
        var x = 2;
    }
    
    var x = 5;
    

    even though you can do this

    for (int i = 0; i < 10; i++)
    {
        var k = 12;
    }
    
    for (int i = 0; i < 10; i++)
    {
        var k = 13;
    }
    

    It's all a little inconsistent.

    EDIT

    Based on the comment exchange with Eric below, I thought it might be helpful to show how I try to handle loops. I try to compose loops into their own method whenever possible. I do this because it promotes readability.

    BEFORE

    /*
     * doing two different things with the same name is unclear
     */
    for (var index = 0; index < people.Count; index++)
    {
        people[index].Email = null;
    }
    var index = GetIndexForSomethingElse(); 
    

    AFTER

    /*
     * Now there is only one meaning for index in this scope
     */
    ClearEmailAddressesFor(people); // the method name works like a comment now
    var index = GetIndexForSomethingElse();
    
    /*
     * Now index has a single meaning in the scope of this method.
     */
    private void ClearEmailAddressesFor(IList people)
    {
        for (var index = 0; index < people.Count; index++)
        {
            people[index].Email = null;
        }
    }
    

提交回复
热议问题