C#WinForms App中的字典引起空引用

Reb*_*Dev 1 c# dictionary visual-studio winforms

我正在使用Visual Studio 2013来创建Visual C#Windows窗体应用程序,而我没有使用Designer来设置窗体.

我正在尝试使用Dictionary来存储位图,以便我可以稍后通过名称调用它们.但是当我调试脚本时,我收到错误:

An unhandled exception of type 'System.NullReferenceException' occurred in SimpleForm.exe
Additional information: Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

从行:

width = imgLetters["a"].Width;
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

减少仍会产生错误的代码版本:

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;

        }


    }

}
Run Code Online (Sandbox Code Playgroud)

Tho*_*mar 6

Dictionary<string, Bitmap> imgLetters;从中删除该行ImgInitialize.这将创建一个与成员变量同名的局部变量.然后填充,但从未使用,而成员变量保持未初始化.

Tipps避免这样的问题:

  1. 您可以以特殊方式命名实例成员,以明确变量是实例成员(例如,m_member而不是member).
  2. 您可以使用实例成员的访问前缀来this.清除您要访问的变量.
  3. 您可以尝试避免将本地变量命名为与实例成员相同.