只使用“if-else"语句的“else"部分是否可以接受?

Is it acceptable to only use the #39;else#39; portion of an #39;if-else#39; statement?(只使用“if-else语句的“else部分是否可以接受?)
本文介绍了只使用“if-else"语句的“else"部分是否可以接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,我觉得检查所有条件是否为真更容易,但只处理其他"情况.

Sometimes, I feel like it is easier to check if all of the conditions are true, but then only handle the "other" situation.

我想我有时觉得更容易知道某事是有效的,并假设所有其他情况都是无效的.

例如,假设我们只有在出现问题时才真正关心:

For example, let's say that we only really care about when there is something wrong:

object value = GetValueFromSomeAPIOrOtherMethod();

if((value != null) && (!string.IsNullOrEmpty(value.Prop)) && (possibleValues.Contains(value.prop)))
{
    // All the conditions passed, but we don't actually do anything
}
else
{
    // Do my stuff here, like error handling
}

或者我应该将其更改为:

Or should I just change that to be:

object value = GetValueFromSomeAPIOrOtherMethod();

if((value == null) || (string.IsNullOrEmpty(value.Prop)) || (!possibleValues.Contains(value.prop)))
{
    // Do my stuff here, like error handling
}

或者(我觉得很难看):

Or (which I find ugly):

object value = GetValueFromSomeAPIOrOtherMethod();

if(!((value != null) && (!string.IsNullOrEmpty(value.Prop)) && (possibleValues.Contains(value.prop))))
{
    // Do my stuff here, like error handling
}

推荐答案

虽然对我来说很少见,但有时我觉得在某些情况下以这种形式编写会导致最清晰的代码.选择最清晰的形式.编译器不会在意,应该生成基本(可能完全)相同的代码.

Though rare for me, I sometimes feel that writing in this form leads to the clearest code in some cases. Go for the form that provides the most clarity. The compiler won't care, and should generate essentially (probably exactly) the same code.

不过,在 if () 语句中定义一个分配条件的布尔变量可能更清楚,然后将代码编写为该变量的否定:

It may be clearer, though, to define a boolean variable that is assigned the condition in the if () statement, then write your code as a negation of that variable:

bool myCondition = (....);
if (!myCondition)
{
    ...
}

这篇关于只使用“if-else"语句的“else"部分是否可以接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)