如何检查颜色值是否等于Null ?
本文关键字:是否 Null 颜色值 何检查 检查 | 更新日期: 2023-09-27 18:11:59
我需要帮助尝试查找所选颜色是否为空。
因为如果我没有选择颜色,我会得到一个错误
这是我得到错误的代码:
private void btnreturn_Click(object sender, RoutedEventArgs e)
{
int gettext;
int.TryParse(txtcount.Text, out gettext);
Color Colorpicker;
//this is where I am getting my error and I need to
//check to see if the selected colour is not null before taking its value
Colorpicker = (Color)colorpicker.SelectedColor;
MainWindow win2 = new MainWindow(gettext, Colorpicker);
win2.Show();
Close();
}
似乎当您不从colorpicker
中选择颜色时,colorpicker.SelectedColor
是null
,并导致您的错误。
你可以在你的代码中检查这个,像这样:
private void btnreturn_Click(object sender, RoutedEventArgs e)
{
int gettext;
int.TryParse(txtcount.Text, out gettext);
Color Colorpicker;
// Check if the SelectedColor is not null, and do stuff with it
if (colorpicker.SelectedColor != null)
{
Colorpicker = (Color)colorpicker.SelectedColor;
MainWindow win2 = new MainWindow(gettext, Colorpicker);
win2.Show();
Close();
}
else
{
// You didn't select a color... do something else
}
}
旁注:如果你正在使用c# 6,你想确保你的colorpicker
对象不是null
,在你的if
检查-你也可以使用colorpicker?.SelectedColor
。注意?
的使用,它在检查底层对象的属性之前检查它是否为空。
我还建议你把变量命名得更清楚一点,更有意义一点…
例如,您的Color Colorpicker;
变量声明。这不是更适合Color selectedColor;
吗?
希望这对你有帮助!
If (Colorpicker != null)
{
//Do code
}
else
{
}
检查'Colorpicker'是否不等于null。
不能发表评论,所以如果这不是你需要的,我道歉c:
会这样工作吗?在尝试添加它之前检查它是否为空。或者用不同的值初始化变量。
private void btnreturn_Click(object sender, RoutedEventArgs e)
{
int gettext;
int.TryParse(txtcount.Text, out gettext);
Color Colorpicker;
//this is where i am getting my error and i need to
//check to see if the selected colour is not null before taking it's value
if(colorpicker.SelectedColor != null){
Colorpicker = (Color)colorpicker.SelectedColor;
MainWindow win2 = new MainWindow(gettext, Colorpicker);
win2.Show();
Close();
} else {
//do something else
}
}
编辑:根据@Geoff James,(颜色)的投射被删除