. Net (C #): When the Declaration variable of the For Loop is captured by the delegate

Source: Internet
Author: User

The reason for discovering a bug in the program is that the declaration variable (that is, the common variable I) is captured by delegate in the for loop ), this happens when you capture the Declaration variable of the for loop, but call the delegate only after the declaration variable has changed. You expect the value of the variable to be captured, but the result is the final value of the variable, even if the variable type is a value type. Let's look at this Code:

VaR list = new action [5];

For (INT I = 0; I <5; I ++)

{

List [I] = new action () => console. writeline (I ));

}

 

Foreach (var a in List)

A ();

 

Obviously, I expect each action to capture the current value, but the output will be:

5

5

5

5

5

 

In for, the life variable is actually a local global variable, just like this:

Int I = 0;

For (; I <5; I ++)

{/*...*/}

 

The solution is to save the current value by declaring a local temporary variable without the Declaration variable of this for loop:

For (; I <5; I ++)

{

VaR local = I;

List [I] = new action () => console. writeline (local ));

}

 

In this way, five will not be output.

 

Of course, this problem will not occur if list. foreach is used. Code:

VaR list = new action [5];

Enumerable. Range (0, 5). tolist (). foreach (I =>

{

List [I] = new action () => console. writeline (I ));

});

 

Foreach (var a in List)

A ();

 

Output:

0

1

2

3

4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.