我正在我的程序中创建一个保存选项,将更改保存到一个文件中。我正在使用此代码保存并获取 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/