我在系统中嵌入了我的资源,我搜索它们的字符串与图像的名称匹配但我仍然得到ArgumentNullException ...为什么会这样?
//Check if currencies are chosen
private void Action()
{
label1.Text = null;
//Checks if items are selected then what currencies are chosen
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
}
else
{
LB1 = listBox1.SelectedItem.ToString();
LB2 = listBox2.SelectedItem.ToString();
Conversion();
}
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image;
}
提前非常感谢你!
答案 0 :(得分:1)
你有一个小的逻辑缺陷。您正在if
条件内设置变量,但在外部使用它们,即使if
条件未执行。
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
}
else
{
LB1 = listBox1.SelectedItem.ToString(); //Doesn't always run
LB2 = listBox2.SelectedItem.ToString();
Conversion();
}
//Always runs
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image;
您应该将其更改为更像这样的内容:
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
}
else
{
LB1 = listBox1.SelectedItem.ToString();
LB2 = listBox2.SelectedItem.ToString();
Conversion();
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image; }
}
或者更好的是,使用guard并使用局部变量,这样编译器将来会遇到这种缺陷:
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
return;
}
var lb1 = listBox1.SelectedItem.ToString();
var lb2 = listBox2.SelectedItem.ToString();
Conversion(lb1, lb2);
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(lb2) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(lb2) as Image;