簡體   English   中英

如何擺脫函數中的此錯誤消息?

[英]How do I get rid of this error message in my function?

我在一個類中有一個函數,但是在“提現”下收到錯誤,“並非所有代碼路徑都返回一個值”。 我以為添加空隙可以解決問題,但似乎無法消除它。 知道如何修改代碼嗎? 這是一部分:

public virtual double Withdraw(double amount)
  {
     if (amount > balance)
     {
        MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
     else
        return balance - amount;
  }

由於您已聲明函數返回double ,因此無論if采用if ,都需要執行該操作。

MessageBox返回之后,您需要從iftrue面返回一個值,例如:

if (amount > balance)
{
    MessageBox.Show(...);
    return balance;
}
else ...

這不是一個直接的答案,但我認為您的Method有許多用途,可以進行計算並向用戶顯示一條消息,您應該考慮使用這樣的兩種方法

public virtual double Withdraw(double amount)
{
    if (amount > balance)    
        throw new Exception("your message")        
    else
        return balance - amount;
}

呼叫者的代碼

try{
 Withraw(...)
}
catch{
 Your messageBox
}

您的ode在任何情況下都應始終返回一些值,因此

public virtual double Withdraw(double amount)
  {
     if (amount > balance)
     {
        MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return SOME_NON_VALID_VALUE_FOR_YOUR_APP; //or raise an exception,
        // depends on architecture 
     }

     return balance - amount;       
  }

考慮提供的代碼的邏輯,如果amount > balance不正確,否則返回計算。

您下面的代碼行未返回任何值是主要的根本原因:

if (amount > balance)
 {
    MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
 }

您應該在MessageBox.Show之后返回一個雙MessageBox.Show值。

您需要在MessageBox.Show之后撤消某些操作。顯示理想狀態0

  public virtual double Withdraw(double amount)
  {
     if (amount > balance)
     {
        MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 0;
     }
     else
        return balance - amount;
  }

您的函數應該返回一個雙精度值,但是如果amount>balance則不會。

public virtual double Withdraw(double amount)
{
    if (amount > balance)
    {
        //your messagebox code    
        return double.NaN; // or whatever you think is correct in this case.
    }
    else
        return balance - amount;
}

您正在通過函數返回double值。

但僅在其他部分中提及。

如果,if(金額>余額)條件為true,則還必須返回該值。

請參閱以下代碼:

    public virtual double Withdraw(double amount)
      {
         if (amount > balance)
         {
            MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         }
         else
            return balance - amount;

         return 0;
      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM