开发者

Why there is no local variable capture? C# closure bahavior

I wrote this convert code in a IMultiValueConverter

public object Convert(object[] values ...)
{
   return new Microsoft.Practices.Compo开发者_开发知识库site.Presentation.Commands.DelegateCommand<object>(
                delegate
                {
                    foreach (ICommand cmd in values)
                    {
                        cmd.Execute(null);
                    }
                });
}

values parameters were two command objects, but when the callback executes (WPF mulibinding) values array includes only null values. Why? How to resolve this problem?


Nothing in your method is changing the value of values, so in this case it's as if the variable values was being captured directly. The normal caveats about the variable being captured aren't applicable - unless, of course, you've got more code in the method which you haven't shown us...

Note that if something else changes the values within the array after the method has returned but before the delegate executes, those changes will still be seen. If you don't want that, you should clone the array yourself:

public object Convert(object[] values)
{
   object[] copy = (object[]) values.Clone();
   return new DelegateCommand<object>(
                delegate
                {
                    foreach (ICommand cmd in copy)
                    {
                        cmd.Execute(null);
                    }
                });
}

It's not really clear from your question what's happening, but hopefully that will help...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜