我需要查看路径是否可用,但仅在运行时。因此,如果我的程序检查到文件不存在,它会将invalidPath bool设置为" true",这样它就不会跳转到" File.Exists。 .."只要程序运行,再次查询。
问题是:如果我这样做,如下所示,我认为不可能避免代码冗余。我需要显示一条消息,告知用户有关丢失的文件,但是对于这两个文件使用相同的代码行并不是很优雅,如果"案例。
private bool invalidPath = false
if (!invalidPath)
{
if (File.Exists(temp))
{
//do code
}
else
{
Show.MessageBox("no file found")
invalidPath = true
}
}
else
{
Show.Messagebox("no file found") /*<---thats redundant*/
}
我希望有人可以给我一个想法。
答案 0 :(得分:2)
试试这个:
bool invalidPath = false;
bool fileExistsflag = false;
if (!invalidPath)
{
if (File.Exists(temp))
{
//do code
fileExistsflag = true;
}
else
{
invalidPath = true;
}
}
if (!fileExistsflag || invalidPath)
{
MessageBox.Show("no file found");
}
答案 1 :(得分:1)
是否有理由不想在单个if块中组合布尔语句?
即
private bool invalidPath = false
if (!invalidPath && File.Exists(temp)) {
//do code
}
else {
Show.MessageBox("no file found")
invalidPath = true
}
答案 2 :(得分:0)
您不能使用单个布尔值来保存两个信息(路径已选中且文件存在)。因此,您必须使用第二个布尔值。
伪代码看起来像这样:
bool valid = false;
bool checked = false;
if(!checked)
{
valid = File.Exists("bla");
checked = true;
}
if(!valid)
{
MessageBox("Path does not exist");
}
但是,您的策略可能存在问题。例如,用户可能在程序运行时删除或重命名路径。