在我的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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是在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");
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
if我得到的问题在评论中NullReferenceException: Object reference not set to an instance of an object.通过网络搜索了一下,但无法找到问题所在.AppSettings.stepsCompleted应该存在像AppSettings.appState
你没有初始化AppSettings.stepsCompleted任何地方.实际上,testApp.Settings不会编译.由于您的AppSettings类具有可从表单访问的静态成员,并且假设您只需要一个实例来跟踪状态,您可以通过静态构造函数初始化它们:
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};
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要删除以下行Main:
AppSettings appSettings = new AppSettings();
Run Code Online (Sandbox Code Playgroud)
在第一次访问之前,保证静态构造函数被调用一次
编辑 - 完整的工作样本
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |