문제

Assume I have the following code:

for(int i=0;i<10;i++)
{
    //"i" is captured in the closure passed to LazyCreate
    MyApi.AddLazyCreate(() => new foo(/*other params*/ i)); 
}

This will result in an unintentional behavior since "i" will be 10 for all the added closures.

Is there a safe way to avoid this? e.g. if I design my api using an Expression<func<foo>> if each "AddLazyCreate" examines the expression passed and store copies of those values, then it should be possible to acheive the intended behavior, right? that is, I have to compile each argument from the expression and get the temporal value of the argument and recreate the new expression using the evaluated args. (the expression will always be a "new" expression)

Or am I missing something fundamental here? Are thre edgecases where I will still get weird behaviors?

도움이 되었습니까?

해결책

You can just do this:

for(int i=0; i<10; i++)
{
    int number = i;
    MyApi.AddLazyCreate(() => new foo(/*other params*/ number)); 
}

This will cause it to capture a different number on each iteration of the loop.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top