简体   繁体   English

从嵌套方法中退出void方法

[英]Returning out of void method from nested method

If I have a void method I can do something like this to break out of it early 如果我有一个无效的方法,我可以做这样的事情早日摆脱它

public void CheckIntNotLessThanZero(int value)
{
    if (int < 0)
    {
        return;
    }

    Console.WriteLine("Not less than zero!")
}

However I run that exact same check several times and so I want to put it into its own method so I don't repeat code: 但是我多次运行完全相同的检查,因此我想将其放入自己的方法中,所以我不重复代码:

public void CheckIntNotLessThanZero(int value)
{
    return CheckIntValue(value);

    Console.WriteLine("Not less than zero!")
}

public void CheckIntValue(int value)
{
    if (value < 0)
    {
        return;
    }
}

That's a basic example but is there a way to do this? 那是一个基本的例子,但是有办法吗?

Turn your Check... methods to return bool value, and check it after every call: 打开您的Check...方法以返回bool值,并在每次调用后对其进行检查:

public bool CheckIntValue(int value)
{
    return value < 0;
}

public void CheckIntNotLessThanZero(int value)
{
    if (CheckIntValue(value))
        return;

    Console.WriteLine("Not less than zero!")
}

Note, that you could throw exceptions in Check... methods, but you must not . 请注意,您可以Check...方法中引发异常,但一定不能 To manage execution flow using exceptions is a bad practice. 使用异常来管理执行流程是一种不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM