C # Anonymous problem with method variable variable with IEnumerable <T>

I am trying to iterate through all components, and for those who implement ISupportsOpen, you can open a project. The problem is when an anonymous method is called, then the component variable is always the same element (as coming from the outer scope from IEnumerable)

foreach (ISupportsOpen component in something.Site.Container.Components.OfType<ISupportsOpen>())
{
    MyClass m = new MyClass();  
    m.Called += new EventHandler(delegate(object sender, EventArgs e)
    {                           
        if (component.CanOpenProject(..)) component.OpenProject(..);
    });

    itemsList.Add(m);
}

How to solve it, please?

+3
source share
1 answer

Just do not close the loop variable - copy it:

foreach (ISupportsOpen component in 
         something.Site.Container.Components.OfType<ISupportsOpen>())
{
    ISupportsOpen copy = component;
    MyClass m = new MyClass();  
    m.Called += new EventHandler(delegate(object sender, EventArgs e)
    {                           
        if (copy.CanOpenProject(..)) copy.OpenProject(..);
    });

    itemsList.Add(m);
}

"" copy , . .

( , , , .)

+5

Source: https://habr.com/ru/post/1740893/


All Articles