C#要么返回false,要么什么都不做 [英] C# either return false or do nothing

查看:203
本文介绍了C#要么返回false,要么什么都不做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法不必重复相同的 if construction ,而是调用 StatusCheck()。成功时它不能返回true。 任何人都知道这个问题有更好的标题吗?

I wondering if there's a way to not have to repeat the same if construction but rather call a StatusCheck(). It can't return true when it succeeds. Anyone knows a better title for this question?

bool Enable()
{
    if (!GetStatus(ref status)) { Trace.WriteLine("Error"); return false; }
    // do stuff

    if (!GetStatus(ref status)) { Trace.WriteLine("Error"); return false; }
    // do more stuff

    if (!GetStatus(ref status)) { Trace.WriteLine("Error"); return false; }
    // do even more stuff

    // 6 more times the above

    return true;
}


推荐答案

您可以创建 CheckStatus()如果状态无效则抛出异常的方法,然后在 Enable()方法中处理该异常:

You can create a CheckStatus() method that throws an exception if the status is not valid, then handle that exception in your Enable() method:

public void CheckStatus(int status)
{
    if (!IsValidStatus(status)) {
        throw new InvalidStatusException(status);
    }
}

public bool Enable()
{
    try {
        CheckStatus(status);
        // do stuff

        CheckStatus(status);
        // do more stuff

        CheckStatus(status);
        // do even more stuff

        // 6 more times the above

        return true;

    } catch (InvalidStatusException) {
        Trace.WriteLine("Error");
        return false;
    }
}

这篇关于C#要么返回false,要么什么都不做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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