gpt4 book ai didi

c# - 从方法返回 boolean 值

转载 作者:太空宇宙 更新时间:2023-11-03 20:30:36 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com