[新手求助]关于get、set
大家先看下面的代码:程序代码:
using System; public class AccountTest { // Main method begins execution of C# application public static void Main(string[] args) { Account account1 = new Account( 50.00M ); // create Account object Account account2 = new Account( -7.53M ); // create Account object // display initial balance of each object using a property Console.WriteLine( "account1 balance: {0:C}", account1.Balance ); // display Balance property Console.WriteLine( "account2 balance: {0:C}\n", account2.Balance ); // display Balance property decimal depositAmount; // deposit amount read from user // prompt and obtain user input Console.Write( "Enter deposit amount for account1: " ); depositAmount = Convert.ToDecimal( Console.ReadLine() ); Console.WriteLine( "adding {0:C} to account1 balance\n", depositAmount ); account1.Credit( depositAmount ); // add to account1 balance // display balances Console.WriteLine( "account1 balance: {0:C}", account1.Balance ); Console.WriteLine( "account2 balance: {0:C}\n", account2.Balance ); // prompt and obtain user input Console.Write( "Enter deposit amount for account2: " ); depositAmount = Convert.ToDecimal( Console.ReadLine() ); Console.WriteLine( "adding {0:C} to account2 balance\n", depositAmount ); account2.Credit( depositAmount ); // add to account2 balance // display balances Console.WriteLine( "account1 balance: {0:C}", account1.Balance ); Console.WriteLine( "account2 balance: {0:C}", account2.Balance ); } }
程序代码:
public class Account { private decimal balance; // instance variable that stores the balance // constructor public Account(decimal initialBalance) { Balance = initialBalance; // set balance using property } // end Account constructor // credit (add) an amount to the account public void Credit(decimal amount) { Balance = Balance + amount; // add amount to balance } // end method Credit // a property to get and set the account balance public decimal Balance { get { return balance; } // end get set { // validate that value is greater than or equal to 0; // if it is not, balance is left unchanged if (value >= 0) balance = value; } // end set } // end property Balance } // end class Account
最后运行结果是:
程序代码:
account1 balance: ¥50.00 account2 balance: ¥0.00 Enter deposit amount for account1: 10 adding ¥10.00 to account1 balance account1 balance: ¥60.00 account2 balance: ¥0.00 Enter deposit amount for account2: 10 adding ¥10.00 to account2 balance account1 balance: ¥60.00 account2 balance: ¥10.00
问题:
在Account类中的set和get只判定了value >= 0的情况就返回值,而如果value < 0的话,运行结果Balance则会是0. 为什么没有添加value < 0的情况,返0值呢?