开发者

Is this a bug in Silverlight InkPresenter

开发者 https://www.devze.com 2023-02-04 12:49 出处:网络
Here\'s a self explanatory piece of code: while (myInkPresenter.Children.Count > 0) { myInkPresenter.Children.RemoveAt(myInkPresenter.Chil开发者_开发知识库dren.Count - 1);

Here's a self explanatory piece of code:

while (myInkPresenter.Children.Count > 0)
{
  myInkPresenter.Children.RemoveAt(myInkPresenter.Chil开发者_开发知识库dren.Count - 1);
}

I then thought a better way might be:

foreach (UIElement item in myInkPresenter.Children)
{
  myInkPresenter.Children.Remove(item);
}

However this throws the error: operation is not valid because of the current state of the object. So I had a think and added an additional line of code:

foreach (UIElement item in myInkPresenter.Children)
{
  myInkPresenter.Children.Remove(item);
  if (myInkPresenter.Children.Count == 0) break;
}

and now it works fine.

My question being is this a bug or should I for some reason expect this behaviour?


Your code will only work when there's only one child. It will break if there are more - it will try to find the "next" item, and notice that its internal collection has changed, thus invalidating the iterator.

This has nothing to do with InkPresenter per se - almost all collections in .NET work that way. Basically, you shouldn't modify a collection while you're iterating over it. (The concurrent collections in .NET 4 are a notable set of exceptions to this rule.)

Given that you just want to clear the list of children, why not just call:

myInkPresenter.Children.Clear();

? Simpler, more readable, and more efficient.

0

精彩评论

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