C#中的字典WinForms应用程序导致空引用 [英] Dictionary in C# WinForms App causing null reference
问题描述
我正在使用Visual Studio 2013创建一个Visual C#Windows窗体应用程序,我没有使用设计器来设置窗体。
I'm using Visual Studio 2013 to create a Visual C# Windows Forms Application and I'm not using the Designer to setup the form.
我正在尝试使用字典来存储位图,以便稍后可以通过名称调用它们。但是当我调试脚本时,我得到错误:
I'm trying to use a Dictionary to store Bitmaps so that I can call them later by name. But when I debug the script I get the error:
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;
任何帮助将不胜感激。
删除仍然产生错误的代码版本:
Cut down version of code which still produces the error:
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;
}
}
}
推荐答案
删除行 Dictionary< string,Bitmap> imgLetters;
从 ImgInitialize
。这将创建一个与成员变量名称相同的局部变量。然后填充,但从未使用,而成员变量保持未初始化。
Remove the line Dictionary<string, Bitmap> imgLetters;
from ImgInitialize
. This creates a local variable with the same name as the member variable. It is then filled, but never used, while the member variable remains uninitialized.
提示避免这样的问题:
- 您可以以特殊方式命名实例成员,以清除变量是一个实例成员(例如
m_member
而不是member
)。 - 您可以使用
这个清除您要访问的变量。
- 您可以尝试避免将局部变量命名为与实例成员相同。
- You could name instance members in a special way to make clear the variable is an instance member (for example
m_member
instead ofmember
). - You could prefix access to an instance member with
this.
to make clear which variable you want to access. - You could try to avoid naming local variables the same as instance members.
这篇关于C#中的字典WinForms应用程序导致空引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!