How do I get around this lambda expression outer variable issue?

后端 未结 4 1792
感情败类
感情败类 2021-01-19 18:47

I\'m playing with PropertyDescriptor and ICustomTypeDescriptor (still) trying to bind a WPF DataGrid to an object, for which the data is stored in a Dictionary.

Sinc

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 19:25

    Simply:

            foreach (string s in this.Keys)
            {
                string copy = s;
                var descriptor = new PersonPropertyDescriptor(
                        copy,
                        new Func(() => { return this[copy]; }),
                        new Action(o => { this[copy] = o; }));
                propList.Add(descriptor);
            }
    
    
    

    With captured variables, it is where it is declared that is important. So by declaring the captured variable inside the loop, you get a different instance of the capture-class per iteration (the loop variable, s, is technically declared outside the loop).

    提交回复
    热议问题