使用 else 语句与未使用的赋值
我有一个与此处发布的问题类似的问题:
我在 mvc 控制器中有一个 if 语句,如下所示:
if (submitButton != "Search")
{
ModelState.Clear();
}
TempData["searchParameter"] = searchParameter;
但是,如果条件为 false,则永远不会使用 TempData["searchParameter"]。保留上面的代码或将 TempData["searchParameter"] 赋值放在 else 语句中是否是更好的做法?
I have a similar question to the one posted here:
I have an if statement in an mvc controller that looks like this:
if (submitButton != "Search")
{
ModelState.Clear();
}
TempData["searchParameter"] = searchParameter;
however if the condition is false, TempData["searchParameter"] is never used. Is it a better practice to leave the code as above or put the TempData["searchParameter"] assignment in an else statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将其放入
else
语句中。它使逻辑流程更加明确,并且省略了不必要的操作,这对性能产生了积极的影响。
Put it in an
else
statement.It makes the logic flow more explicit and an unnecessary operation is omitted, which affects the performance positively.
Id 使用 else 语句。如果将来发生任何变化,会变得更加清晰和安全。
我想这也是一个很好的做法。
Id use the else statement. Makes it clearer and securer if any changes are made in the future.
I guess its also good practice.
在您的示例中,无论是否
submitButton != "Search"
都会分配TempData["searchParameter"]
。这是您所期望的行为吗?如果没有,
else
语句将为您解决此问题。In your example,
TempData["searchParameter"]
is assigned to regardless of of whethersubmitButton != "Search"
. Is this the behaviour you are expecting?If not, an
else
statement will resolve this for you.在您的具体情况下,当可以轻松避免时,运行不必要的代码绝不是一个好主意。在这种情况下,这似乎没什么大不了的,但这不是一个好习惯。
更一般地说,我总是使用 else 语句,即使代码流在没有它的情况下是相同的。例如:
else 并不是绝对必要的,一些代码分析工具会建议删除它。但我更喜欢这样的明确性:只需看一眼代码的结构就能知道实际上只有其中一个块会被执行。如果没有 else,您必须分析第一个块以确定它不包括第二个块。
In your specific case, running unnecessary code is never a good idea when it can be easily avoided. It may not seem like a big deal in this case, but it is not a good habit to get into.
More generally, I always use an else statement even when the code flow would be identical without it. For example:
The else is not strictly necessary, and some code analysis tools will recommend removing it. But I prefer the explicitness of being able to tell just by glancing at the structure of the code that only one of those blocks is actually going to be executed. Without the else, you have to analyze the first block to determine that it is exclusive of the second block.