简体   繁体   English

确定在 C# 中的 if 语句中哪个表达式不正确

[英]Determine which expression was not true in if-statement in C#

Let's say I have the following piece of code:假设我有以下代码:

infile = new FileInfo(inputFilename);
outfile = new FileInfo(outputFilename);

if (!infile.Exists || !outfile.Exists) {
  Console.WriteLine("File missing: " + ???);
}

Is it possible to determine which of the single "if statements" was not true?是否有可能确定哪个“if 语句”不正确? ??? shall be replaced with the filename of the non-existing file.应替换为不存在的文件的文件名。

Why don't you just split your if into two?你为什么不把你的if分为二?

if (!infile.Exists) {
  Console.WriteLine("File missing: " + infile);
}
if (!outfile.Exists) {
  Console.WriteLine("File missing: " + outfile);
}

You could collect the files that do not exist and then use that collection to print the error message.您可以收集不存在的文件,然后使用该集合打印错误消息。 For example:例如:

var missingFiles = new FileInfo[] {inFile, outFile}.Where(f => !f.Exists);
foreach (var missingFile in missingFiles) {
    Console.WriteLine("File missing: " + missingFile);
}

No, not directly.不,不是直接的。 However, you could write但是,你可以写

bool infileExists = infile.Exists;
bool outfileExists = outfile.Exists;
if (!infileExists || !outfileExists) {
  Console.WriteLine("File missing: " + infileExists?"Outfile":"Infile");
}

This doesn't even need an additional evaluation of the property.这甚至不需要对财产进行额外的评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM