我有計數的時間用戶已經從ATM提取的金額(作爲是有一定限度),並且還向上計數的錢用戶在一天已經取出的量的方法。然而,計數變量和amountWithdrawn
變量中的值在離開方法時都丟失了,我如何讓它們「保存」?
另外作爲一個便箋,我有一個名爲Account
的課程,其中有餘額等,最好把它們放在那裏?但也想知道是否有可能將變量保存在方法中供將來參考。如何在離開方法時保存變量值?
public decimal WithDraw()
{
int timesWithdrawn = 9;
decimal amountWithdrawnToday = 0;
decimal money = 0;
bool success = false;
if (timesWithdrawn < 10)
{
do
{
//Console.WriteLine("{0} available to withdraw.", FundsAvailable);
Console.WriteLine("How much would you like to withdraw?");
try
{
money = decimal.Parse(Console.ReadLine());
if (money % 5 == 0 && money <= account.CurrentBalance && money <= 1000)
{
success = true;
}
if (money == 0)
{
bool exit = true;
Console.WriteLine("Do you want to exit? Type \"yes\", or \"no\".");
while (exit == true)
{
string response = Console.ReadLine();
if (response.ToLower() == "yes")
{
break;
}
else
{
exit = false;
}
}
}
}
catch (FormatException)
{
Console.WriteLine("Please enter a number to withdraw.");
}
} while (success == false);
//do while this is true
Console.WriteLine(account.CurrentBalance);
Console.WriteLine("Withdrawing {0} pounds.", money);
Console.WriteLine("You have {0} remaining in your account.", account.CurrentBalance - money);
amountWithdrawnToday += money;
timesWithdrawn += 1;
Console.WriteLine("{0} pounds withdrawn today", amountWithdrawnToday);
return account.CurrentBalance -= money;
}
else
{
Console.WriteLine("You have exceeded daily withdrawls. You have withdrawn {0}", amountWithdrawnToday);
return amountWithdrawnToday;
}
}
在我看來,對於這個特定的使用,最好能夠使用的帳戶類,因爲它保存有關的帳戶信息。此外,可以創建一個「包裝器」類,從包含方法外所需信息的方法返回。另一種選擇是使用out或ref參數。發送參數會在發送它們的上下文中更改它們。你可以閱讀更多關於它這裏[鏈接](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters) –