检测到无法访问的代码,如何使用if和else语句修复此问题?

时间:2014-10-07 21:28:49

标签: c# visual-studio-2010 account

我遇到了解决这个问题的问题。我得到的是检测到无法访问的代码。我可以使用该警告运行该程序,但它无法正常工作。我不明白的是什么?

这是我的代码的最后一部分:

class Account
    {        
       private double balance = 0;


       public Account()
       {
       }//end construcor

        //Constructor initializes balance with an amount supplied as argument
       public Account(double amount)
        {
            Balance = amount;
        }// end constructor    

       //property to get and set the balance value
        public double Balance
        {
            get
            {
                return balance;
            }
            set
            {
                balance = value;
            }
        }// end property


        public void ShowMessage(string str)
        {
            Console.WriteLine(str);
        }


        public double Deposit(double depositAmount)
        {

            Balance += depositAmount * 1.05;
            return Balance ;
        }

        public double Withdraw(double WithdrawAmount)
        {
            Balance -= WithdrawAmount;
            return Balance;

            if (WithdrawAmount > this.Balance)
                this.ShowMessage("You do not have enough money!");
            else
                this.Balance -= WithdrawAmount;
            return this.Balance;
        }
    }
}

3 个答案:

答案 0 :(得分:3)

Withdraw的整个最后一个块无法访问,因为第二行中有return,它将参数返回给调用者并退出函数。

看起来就像你应该完全删除前两行一样。

答案 1 :(得分:1)

您的第二行return Balance;将退出该方法,因此永远不会达到if / else。

答案 2 :(得分:1)

这是问题所在:

public double Withdraw(double WithdrawAmount)
    {
        Balance -= WithdrawAmount;
        return Balance;

        if (WithdrawAmount > this.Balance)
            this.ShowMessage("You do not have enough money!");
        else
            this.Balance -= WithdrawAmount;
        return this.Balance;
    }

第二行结束了函数的生命。

  Balance -= WithdrawAmount;  
  return Balance;

这是我的解决方案:

The Withdraw logic as I see it: 

 if (Balance < WithdrawAmount)
 {
    ShowMessage("You do not have enough money!");
 }
 else
 {
    Balance -= WithdrawAmount;
 }

 return Balance;

如果您无法提款,请打印一条消息,否则您将提取金额。

在任何情况下,您都会返回当前余额。