【发布时间】:2013-11-14 12:58:30
【问题描述】:
我正在使用 Visual Studio 2013 创建 Visual C# Windows Forms 应用程序,但我没有使用 Designer 来设置表单。
我正在尝试使用字典来存储位图,以便以后可以按名称调用它们。但是当我调试脚本时,我得到了错误:
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;
}
}
}
【问题讨论】:
-
你有两个变量叫做
imgLetters,一个在整个类中可见,第二个在ImgInitialize中创建。发生的事情是:当您为ImgLetters分配一个值时,您分配给ImgInitialize中指定的变量/对象,而不是类中的私有变量/对象。这意味着类中的 imgLetters 具有默认值,即NULL,从ImgInitialize中删除 imgLetters 的声明或按照答案之一中的建议使用this关键字。
标签: c# winforms visual-studio dictionary