【发布时间】:2017-05-27 09:52:43
【问题描述】:
我有一个方法可以计算用户从 atm 取款的次数(因为有限制),还可以计算用户当天取款的金额。但是,count var 和 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 参数。发送参数会在发送它们的上下文中更改它们。你可以在这里阅读更多关于它的信息link
标签: c#