gpt4 book ai didi

c# - C# WinForms App 中的字典导致空引用

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:53 25 4
gpt4 key购买 nike

我正在使用 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;

}


}

}

最佳答案

删除行 Dictionary<string, Bitmap> imgLetters;来自 ImgInitialize .这将创建一个与成员变量同名的局部变量。然后它被填充,但从未被使用,同时成员变量保持未初始化状态。

避免此类问题的提示:

  1. 您可以用特殊的方式命名实例成员,以表明变量是实例成员(例如 m_member 而不是 member )。
  2. 您可以使用 this. 作为访问实例成员的前缀明确您要访问哪个变量。
  3. 您可以尽量避免将局部变量命名为与实例成员相同。

关于c# - C# WinForms App 中的字典导致空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19978252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com