我正在程序中保存一个选项,将更改保存到文件中。我正在使用此代码保存并获取MessageBox
以显示过程的结果我在“对象引用未设置为对象的实例”这一行上遇到错误。
SaveFileCheck = StockHandler.SaveChangesToFile();
这是我的代码
private void Save_Click(object sender, EventArgs e)
{
bool SaveFileCheck = false;
var result = MessageBox.Show("Are you sure you want to Save the changes ?", "My Application",
MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (result == DialogResult.Yes)
{
SaveFileCheck = StockHandler.SaveChangesToFile();
if (SaveFileCheck)
{
MessageBox.Show("The process was a success");
}
else
{
MessageBox.Show("The process failed please make sure that the file is not been used and try again");
}
//Save the file back
}
}
}
}
public bool SaveChangesToFile()
{
try
{
if (FileName != null)
{
using (StreamWriter Write = new StreamWriter(FileName, false))
{
foreach (Stock s in FileStockList)
{
Write.Write(s.ToString() + "\r\n");
}
}
}
else {
return false;
}
}
catch(IOException ex)
{
return false;
throw new ArgumentException("something went wrong an error" + ex + "is been cought");
}
return true;
}
最佳答案
StockHandler
为空。
如果StockHandler
不是static
类,则需要创建它的实例,然后才能对其调用方法:
var handler = new StockHandler();
SaveFileCheck = handler.SaveChangesToFile();
或者,如果
StockHandler
是成员变量:StockHandler = new // something
关于c# - 从方法返回 boolean 值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7773837/