为什么我的函数告诉我检测到无法访问的代码? C#

Why does my function tell me there's an unreachable code detected? c#

我创建了这个函数:

public bool checkFunds(int x)
        {
            if(checksBox.CheckState == CheckState.Checked && OriginalMain.temporaryChecks >= x)
            {
                return true;
            }
            else
            {
                MessageBox.Show("Error! Insufficient funds");
                return false;
            }

            if(savingsBox.CheckState == CheckState.Checked && OriginalMain.temporarySavings >= x)
            {
                return true;
            }
            else
            {
                MessageBox.Show("Error! Insufficient funds!");
                return false;
            }
        }

此代码用于 windows 表单申请。我正在制作一个银行模拟器,您可以在其中选择两个不同的帐户来取出您的钱。此功能特别检查您选择了哪个复选框,并检查所选帐户上是否有足够的可用资金。但是 C# 一直告诉我第二个 if 是无法访问的代码。这是为什么?我该如何解决?

您收到警告,因为您的函数必然会在这些位置之一退出:

if(checksBox.CheckState == CheckState.Checked && OriginalMain.temporaryChecks >= x)
{
    return true;   // <-- if the condition is true, your function will exit here
}
else
{
    MessageBox.Show("Error! Insufficient funds");
    return false;   // <-- if the condition is false, your function will exit here
}
// this means this place in code is NEVER reached, so you get the warning
if(savingsBox.CheckState == CheckState.Checked && OriginalMain.temporarySavings >= x)

您很可能需要与此类似的逻辑:

if(checksBox.CheckState == CheckState.Checked)
{
    if(OriginalMain.temporaryChecks >= x)
    {
        return true;
    }
    else
    {
        MessageBox.Show("Error! Insufficient funds");
        return false;
    }
}
if(savingsBox.CheckState == CheckState.Checked)
{
    if(OriginalMain.temporarySavings >= x)
    {
        return true;
    }
    else
    {
        MessageBox.Show("Error! Insufficient funds!");
        return false;
    }
}