我正在使用 Visual Studio 2013 创建 Visual C# Windows 窗体应用程序,但我没有使用设计器来设置表单。
我正在尝试使用字典来存储位图,以便以后可以按名称调用它们。但是当我调试脚本时,我得到了错误:
An unhandled exception of type 'System.NullReferenceException' occurred in SimpleForm.exe
Additional information: Object reference not set to an instance of an object.
从线:
width = imgLetters["a"].Width;
任何帮助将不胜感激。
减少仍然产生错误的代码版本:
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace SimpleForm
{
public class Test : Form
{
static Bitmap bmpLetterA;
static Bitmap bmpLetterB;
static Bitmap bmpLetterC;
private Dictionary<string, Bitmap> imgLetters;
public Test()
{
ImgInitialize();
ImgWidth();
}
private void ImgInitialize()
{
Dictionary<string, Bitmap> imgLetters;
bmpLetterA = new Bitmap("a.png");
bmpLetterB = new Bitmap("b.png");
bmpLetterC = new Bitmap("c.png");
imgLetters = new Dictionary<string, Bitmap>();
imgLetters.Add("a", bmpLetterA);
imgLetters.Add("b", bmpLetterB);
imgLetters.Add("c", bmpLetterC);
}
private void ImgWidth()
{
int width = 0;
width = imgLetters["a"].Width;
}
}
}