在方法返回的If-Else语句中,是否可以明确声明是否可以隐式遵循? [英] In an If-Else Statement for a method return, should an Else be explicitly stated if it can instead be implicitly followed?

查看:173
本文介绍了在方法返回的If-Else语句中,是否可以明确声明是否可以隐式遵循?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个检查某些东西的方法,并根据这些检查返回一个布尔值。它涉及单个分支If部分按顺序检查约5个条件。如果这些条件中的任何一个返回true,则该方法将返回true; 。如果没有条件返回true,则方法将返回false; 。由于If部分之后的代码只会在没有条件为真的情况下运行,因此该代码在逻辑上与包含实际的Else语句相同。

I have a method that checks certain things and returns a Boolean based on those checks. It involves a single branching If section that checks about 5 conditions in sequence. If any of those conditions return true, then the method will return true;. If none of the conditions return true, then the method will return false;. Since the code after the If section will only run if none of the conditions are true, then that code is logically identical to including an actual Else statement.

那么在这种情况下实际写入Else语句更好吗?

So is it a better idea to actually write in the Else statement for this kind of situation?

编辑

事实证明,我需要有关哪些条件实际上为某些条件的真实触发的信息,所以我将方法更改为返回一个int,-1代表假情况。逻辑仍然存在,如果没有条件成立,它将返回-1。所以,我不再有返回的可缩减选项(cond1 || cond2 || cond3 || cond4 || cond5); ,但我也感谢大家的建议,因为我确实没有想过它(主要是因为cond3是一个非常复杂的条件,涉及在两对DateTime对象的中点检查交集,所以看起来很难看)。虽然方法的性质发生了变化,但这个问题的性质还没有,而且所有的答案基本上都是适用的......

It turns out that I needed information on which condition actually tripped the "true" for some of these, so I changed the method to return an int, with -1 representing the "false" situation. The logic still remains, if none of the conditions are true, it'll return -1. So, I no longer have the condensable option of return (cond1 || cond2 || cond3 || cond4 || cond5);, but I thank everyone for that suggestion too, since I had indeed not thought about it (primarily because cond3 is a very complex condition involving checking for intersection in the midpoints of two pairs of DateTime objects, so it would look ugly). While the nature of the method has changed, the nature of this question has not and all answers are still basically applicable...

这个代码目前用来解释它删除所有定义cond1到cond5的无关代码...

The code is currently, to paraphrase it and cut out all the extraneous code that defines cond1 thru cond5...

if (cond1) { return 1; }
else if (cond2) { return 2; }
else if (cond3) { return 3; }
else if (cond4) { return 4; }
else if (cond5) { return 5; }


推荐答案

我倾向于喜欢这样的东西来回归值。

I tend to prefer something like this to returning hard values.

static bool SomeFunc(string arg)
{
    bool result = false;

    if (arg.Length < 10)
    {
        result = true;
    }
    else if (arg.StartsWith("foo"))
    {
        result = true;
    }

    if (!result && arg.EndsWith("foo"))
    {
        result = true;
    }

    return result;
}

这篇关于在方法返回的If-Else语句中,是否可以明确声明是否可以隐式遵循?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆