将值赋给int类型时遇到麻烦

本文关键字:遇到 麻烦 类型 int | 更新日期: 2023-09-27 18:12:09

我在给int PlanPrice赋值时遇到了麻烦。我已经删去了很多代码,但是当用户按下"a"键时,AddCustomer函数被调用,他们可以输入大量数据,这些数据可以毫无问题地保存下来。但是在AddCustomer函数的末尾,我使用一个开关来确定他们当前计划的价格。然而,当我尝试使用PlanPrice int后,这个函数已经返回到Main,值总是0。我可以看到,在AddCustomer函数中,值实际上确实被分配了,但是当我回到Main中的开关时,由于某种原因,保持在0,尽管AddCustomer中用户的所有其他数据实际上都保存并正常工作。

主:

int PlanPrice = 0;
...
switch (menuSelection)
{
     case "a": AddCustomer(..., PlanPrice); break;
     case "c": CalculatePayment(..., PlanPrice); break; //Displays 0
     ...
     case "z": Console.WriteLine(PlanPrice); break; //Displays 0
}

AddCustomer:

static void AddCustomer(..., int PlanPrice)
{
     ...
     Console.Write("Current Plan (S, M, L or XL): ");
     currentPlan[arrayLength] = Console.ReadLine();
     switch (currentPlan[arrayLength]) 
     {
         case "S": { planPrice = 55; } break;
         case "M": { planPrice = 70; } break;
         case "L": { planPrice = 95; } break;
         case "XL": { planPrice = 135; } break;
         default:
         {
             Console.WriteLine("'nSorry, you can only enter S, M, L or XL'n");  
         }
     }
}

将值赋给int类型时遇到麻烦

如果你的方法需要修改一个参数,它必须被标记为outref

static void AddCustomer(..., out int PlanPrice)
{
}

选项1

refout通过PlanPrice

out关键字导致参数通过引用传递。这是与ref关键字类似,只是ref要求变量为在传递之前初始化。若要使用out参数,则方法定义和调用方法必须显式地使用out字。

所以在你的情况下,out似乎更适合

static void AddCustomer(..., out int PlanPrice)
{
   ... 
}

选项2

因为你的AddCustomer是静态的,你可以在你的情况下使用另一种选择,是使PlanPrice成为static,然后你不需要PlanPrice成为AddCustomer的参数:

static int PlanPrice;
static void AddCustomer(...)
{
   //PlanPrice is accessible here, because it is static and your method is static too.
}