我有这段代码给我带来了麻烦。
最后一个break语句给出了“检测到无法访问的代码”的错误
这导致了我的计划中的逻辑缺陷。
有人能确定问题吗?
谢谢!
case 127232:
case1 = splited[0];
changeRow[inServer] = "Audit Privileges and Logs:\n";
changeRow[inServer + " Exception"] = "No Exception";
writeToFile(Directory.GetCurrentDirectory() + @"\" + inServer + "127232.txt", case1);
if (case1.Contains("audit level;failure") || case1.Contains("audit level;all"))
{
Console.WriteLine("success!");
changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) Audit options found .";
changeRow[inServer] = changeRow[inServer] + "string pattern audit level;failure or auditlevel;all found";
break;
}
else
{
//Audit Privileges should have been in enabled for sys and system accounts or the security administrator.
changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) No audit options found.";
changeRow[inServer] = changeRow[inServer] + "Correct audit options not configured!";
changeRow[inServer + " Exception"] = "Exception";
break;
}
break;
答案 0 :(得分:7)
then
子句的else
和if
部分都包含break
。显然,if
之后的代码永远不会被执行。
答案 1 :(得分:4)
break
和if
条款中都有else
,这意味着永远无法触及底部的break
。
在这种特殊情况下,这并不重要,但似乎编译器不够“聪明”,不足以解决这个问题。对于编译器而言,这并不一定是一种糟糕的态度,因为这可以被认为是草率的编码实践。
只需删除break
和if
子句中的else
个语句,或者重构为:
case 127232:
case1 = splited[0];
changeRow[inServer] = "Audit Privileges and Logs:\n";
changeRow[inServer + " Exception"] = "No Exception";
writeToFile(Directory.GetCurrentDirectory() + @"\" + inServer + "127232.txt", case1);
if (case1.Contains("audit level;failure") || case1.Contains("audit level;all"))
{
Console.WriteLine("success!");
changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) Audit options found .";
changeRow[inServer] = changeRow[inServer] + "string pattern audit level;failure or auditlevel;all found";
break;
}
//Audit Privileges should have been in enabled for sys and system accounts or the security administrator.
changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) No audit options found.";
changeRow[inServer] = changeRow[inServer] + "Correct audit options not configured!";
changeRow[inServer + " Exception"] = "Exception";
break;
你原版中的内容与以下内容并没有多大区别:
if (someCondition) {
doSomething();
return;
} else {
doSomethingElse();
}
我一直认为它更清洁:
if (someCondition) {
doSomething();
return;
}
doSomethingElse();
我不喜欢被代码标记为死亡,除非绝对必要: - )
答案 2 :(得分:2)
因为您的代码会进入if
或else
,而且它们都包含break
,这会将您带到switch
语句之外,最后一个break
声明是不必要的。
答案 3 :(得分:0)
如果有条件和其他条件,则会有中断。在其他条件之后如何重新打破?