如何从静态 void 方法返回变量

本文关键字:方法 返回 变量 void 静态 | 更新日期: 2023-09-27 18:30:17

我是C#和强类型语言的新手。我正在做大学作业,我的课程现在按预期工作。但是,我更改了 2 个静态 void 方法标题以具有返回类型,但没有意识到这样做会导致扣分。

Current method headings
static bool DispenseCash(double amount, int whichAccount, bool validAmount) and
static double WithdrawAmount(int whichAccount) must remain 
What they need to be.
static void DispenseCash(double amount) and
static void WithdrawAmount(int whichAccount)

我更改了它们,因为我不知道如何从
静态无效 提款金额(int 哪个帐户) 并将其用作参数 静态空洞 分配现金(双倍金额)。

我被迫使用这两种方法,而不是使用一种更大的方法解决问题。

这是我的代码片段,可以更好地解释这一切。为了保持简短,我只包括了相关部分。

int whichAccount = int.Parse(Console.ReadLine());
do
{
double amount = WithdrawAmount(whichAccount);
validAmount = DispenseCash(amount, whichAccount, validAmount);
} while (validAmount == false);
//end of relevant method calls in main
static double WithdrawAmount(int whichAccount)    
{
Console.Write("'nPlease enter how much you would like to withdraw: $");
double amount = double.Parse(Console.ReadLine());       
return amount; 
}
//end WithdrawAmount

在下面的 DispenseCash 方法中,如果它是静态无效的 DispenseCash(双倍金额),我如何将 int 哪个帐户和布尔有效金额传递到其中并从中返回布尔有效金额。

private static bool DispenseCash(double amount, int whichAccount, bool validAmount)
{
int numOf20s;
int numOf50s;
double balenceMinusAmount = (accountBalances[whichAccount]) - Convert.ToInt32(amount); 
if((Convert.ToInt32(amount) >= 1) && (Convert.ToInt32(amount) % 50 == 0) &&   (balenceMinusAmount >= accountLimits[whichAccount]))
{
numOf50s = Convert.ToInt32(amount) / 50;
numOf20s = (Convert.ToInt32(amount) % 50) / 20;

Console.WriteLine("Number of 50's = {0}", numOf50s);
Console.WriteLine("Number of 20's = {0}", numOf20s);
accountBalances[whichAccount] = (accountBalances[whichAccount]) - amount;
return validAmount = true;
}
else
      {
          Console.WriteLine("Invalid entry");
          return validAmount = false;
      }
}

请记住,我根本无法更改方法标题。但是我可以调用其中一个或方法中的新方法。我尝试了一些不同的事情,但所有的尝试都失败了。

如何从静态 void 方法返回变量

正如jdphenix所提到的,我不确定为什么要求你这样做。它违背了基本的编程原则。也许我们不了解手头问题的全部背景。

我能想到的唯一方法是在您的应用程序中利用静态变量。

private static double withdrawalAmount;
private static int selectedAccount;
private static bool isValidAmount;

然后在您需要的方法中使用这些方法,例如:

public static void WithdrawAmount(int whichAccount)
    {
        Console.Write("'nPlease enter how much you would like to withdraw: $");
        withdrawalAmount = double.Parse(Console.ReadLine());
    }