Access to Modified Closure

前端 未结 3 1804
难免孤独
难免孤独 2020-11-22 09:01
string [] files = new string[2];
files[0] = \"ThinkFarAhead.Example.Settings.Configuration_Local.xml\";
files[1] = \"ThinkFarAhead.Example.Settings.Configuration_Glo         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 09:21

    In this case, it's okay, since you are actually executing the delegate within the loop.

    If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the variable i rather than its value at the time of the delegates creation.

    In short, it's something to be aware of as a potential trap, but in this case it doesn't hurt you.

    See the bottom of this page for a more complex example where the results are counterintuitive.

提交回复
热议问题