尝试从资源

时间:2017-10-11 15:04:47

标签: c# string image visual-studio resources

我在系统中嵌入了我的资源,我搜索它们的字符串与图像的名称匹配但我仍然得到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;
    }

Picture of Resource images

提前非常感谢你!

1 个答案:

答案 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;