I have this code:

foreach (UIElement uiElement in list)
{
    uiElement.SetValue(Grid.ColumnProperty, colunmn++);
    uiElement.SetValue(Grid.RowProperty, _uiRoot.RowDefinitions.Count - 1);
    _uiRoot.Children.Add(uiElement);
}

It runs fine, but Code Contracts is giving me a warning: Possibly calling a method on a null reference, uiElement.

How can uiElement ever be null? The list is a List of UIElements so it should iterate through the list without any nulls.

有帮助吗?

解决方案

Because you can put nulls in your list, even though you probably won't

you can do

foreach (UIElement uiElement in list.Where(e => e != null))
{
   uiElement.SetValue(Grid.ColumnProperty, colunmn++);
   uiElement.SetValue(Grid.RowProperty, _uiRoot.RowDefinitions.Count -1);
   _uiRoot.Children.Add(uiElement);
}

其他提示

A list can contain null references. You can insert null into a list. You can also insert a good reference into a list, then set it to null later. For example, if I have a list of People, I can have the list: "Bob", "Fred". Now I grab Bob from the list, do some stuff, and change it to null. A list contains a list of References not items. So it points to the location where the item was. Now when you iterate through the list, location 0 is now null since the reference where Bob was now contains a null.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top