【发布时间】:2012-08-08 01:55:45
【问题描述】:
我创建了两个组合框,一个用于最小值,一个用于最大值。我的代码应确保用户不会使用此代码选择大于最大值的最小值或小于最小值的最大值。
private void MaxRating_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
switch (MaxRating.SelectedIndex)
{
case 0:
if (MinRating.SelectedIndex > 0)
MinRating.SelectedIndex = 0;
break;
case 1:
if (MinRating.SelectedIndex > 1)
MinRating.SelectedIndex = 1;
break;
case 2:
if (MinRating.SelectedIndex > 2)
MinRating.SelectedIndex = 2;
break;
case 3:
if (MinRating.SelectedIndex > 3)
MinRating.SelectedIndex = 3;
break;
case 4:
if (MinRating.SelectedIndex > 4)
MinRating.SelectedIndex = 4;
break;
}
}
但是,在显示“if (MinRating.SelectedIndex > 0)”的行进行调试时,我得到“NullReferenceException 未被用户代码处理”。
我不知道为什么,我也有一个用于 MinRating_SelectionChanged 的函数,但我似乎没有得到类似的东西。
如果我从这个函数中删除 case:0,似乎没有错误。也不是来自其他功能。我也尝试用 == 替换 > 但它似乎做同样的事情。 任何帮助都会受到赞赏,因为我很困惑。
编辑:如果我只放置这两行
int minrating = MinRating.SelectedIndex;
int maxrating = MaxRating.SelectedIndex;
它在第二行给出错误
【问题讨论】:
-
您能否将整个异常文本放入问题中
-
解决这个问题后,您还可以将代码简化为 1 行:
MinRating.SelectedIndex = Math.Min(MinRating.SelectedIndex, MaxRating.SelectedIndex); -
在抛出异常的行添加断点,并检查表达式的每个部分是否有空引用
-
关于编辑:这意味着没有为 MaxRating 选择索引。您正在询问尚未(尚未)进行的选择的结果。
标签: c# .net wpf nullreferenceexception