[英]Determine which expression was not true in if-statement in C#
假設我有以下代碼:
infile = new FileInfo(inputFilename);
outfile = new FileInfo(outputFilename);
if (!infile.Exists || !outfile.Exists) {
Console.WriteLine("File missing: " + ???);
}
是否有可能確定哪個“if 語句”不正確? ???
應替換為不存在的文件的文件名。
你為什么不把你的if
分為二?
if (!infile.Exists) {
Console.WriteLine("File missing: " + infile);
}
if (!outfile.Exists) {
Console.WriteLine("File missing: " + outfile);
}
您可以收集不存在的文件,然后使用該集合打印錯誤消息。 例如:
var missingFiles = new FileInfo[] {inFile, outFile}.Where(f => !f.Exists);
foreach (var missingFile in missingFiles) {
Console.WriteLine("File missing: " + missingFile);
}
不,不是直接的。 但是,你可以寫
bool infileExists = infile.Exists;
bool outfileExists = outfile.Exists;
if (!infileExists || !outfileExists) {
Console.WriteLine("File missing: " + infileExists?"Outfile":"Infile");
}
這甚至不需要對財產進行額外的評估。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.