我有一个包含信息
的Setting.cs文件[Serializable]
public class Setting
{
public Setting() {}
public String defaultAlertTone = Path.GetDirectoryName(Application.ExecutablePath) + "\\Sounds\\applause-2.wav";
}
和我的settingsForm通过此代码检索信息
Setting settingObject;
public SoundPlayer player;
public settingsForm(backgroundForm backgroundFormObject)
{
InitializeComponent();
this.backgroundFormObject = backgroundFormObject;
settingObject = backgroundFormObject.getSetting();
}
private void InitializeSound()
{
// Create an instance of the SoundPlayer class.
player = new SoundPlayer();
player.SoundLocation = settingObject.defaultAlertTone;
// Listen for the LoadCompleted event.
player.LoadCompleted += new AsyncCompletedEventHandler(player_LoadCompleted);
// Listen for the SoundLocationChanged event.
player.SoundLocationChanged += new EventHandler(player_LocationChanged);
}
为什么每次运行应用程序时,
上都会出现空引用异常player.SoundLocation = settingObject.defaultAlertTone;
backgroundFormObject.getSetting();
只是一种检索设置对象的方法。它的代码如下
Setting settingObj = new Setting();
public Setting getSetting()
{
return settingObj;
}
答案 0 :(得分:2)
原因可能是
InitializeSound()
以某种方式在settingsForm
之前运行(不太可能,但这会使settingObject
未初始化并引用null
)。Setting
课程的完整代码,我看不到在任何地方调用new Setting()
会有什么影响。因此,当您在Setting settingObject = new Setting();
类中首次定义此属性时,请使用settingsForm
。settingObject
不是null。