在我的C#练习中遇到了另一个问题。这是对它的简短解释: 在Program.cs中,我有以下代码:
namespace testApp
{
public class AppSettings
{
public static int appState { get; set; }
public static bool[] stepsCompleted { get; set; }
}
public void Settings
{
appState = 0;
bool[] stepsCompleted = new bool[]{false, false, false, false, false};
}
}
static class MyApp
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new gameScreen());
AppSettings appSettings = new AppSettings();
}
}
这是在Form1.Designer.cs中:
namespace testApp
{
private void InitializeComponent() {..}
private void detectPressedKey(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // Enter = code 13
{
if (AppSettings.appState == 0)
{
if (AppSettings.stepsCompleted[1] == false) // << here we have an EXCEPTION!!!
{
this.playSound("warn");
}
}
}
}
}
问题出在评论if
,我得到NullReferenceException: Object reference not set to an instance of an object
。通过网络搜索了一下,但无法找到问题所在。 AppSettings.stepsCompleted
应该存在AppSettings.appState
答案 0 :(得分:5)
您没有在任何地方初始化AppSettings.stepsCompleted
。实际上,testApp.Settings
将无法编译。由于您的AppSettings
类具有您从表单访问的静态成员,并且假设您只需要一个实例来跟踪状态,您可以通过static constructor初始化它们:
public static class AppSettings // May as well make the class static
{
public static int appState { get; set; }
public static bool[] stepsCompleted { get; set; }
static AppSettings() // Static constructor
{
appState = 0;
stepsCompleted = new []{false, false, false, false, false};
}
}
然后,您需要从Main
AppSettings appSettings = new AppSettings();
保证静态构造函数在第一次访问之前被调用一次
修改 - 完整工作示例
Program.cs的
using System;
using System.Windows.Forms;
namespace testApp
{
public static class AppSettings // May as well make the class static
{
public static int appState { get; set; }
public static bool[] stepsCompleted { get; set; }
static AppSettings() // Static constructor
{
appState = 0;
stepsCompleted = new[] { false, false, false, false, false };
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new gameScreen());
}
}
}
Form1.cs(gameScreen)
using System.Windows.Forms;
namespace testApp
{
public partial class gameScreen : Form
{
public gameScreen()
{
InitializeComponent();
}
private void gameScreen_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // Enter = code 13
{
if (AppSettings.appState == 0)
{
if (AppSettings.stepsCompleted[1] == false)
{
this.playSound("warn");
}
}
}
}
private void playSound(string someSound)
{
MessageBox.Show(string.Format("Sound : {0}", someSound));
}
}
}