我正在尝试接受用户输入,然后使用该输入来计算图表,但每次设置该值时,该值都会重置为初始值为零。我知道这是因为方法StraightLineDepreciation()
正在返回一条消息,告诉我我没有输入一个数字,只有在值为0时返回,这就是初始值。它似乎在断开开关循环后重置。这是我的计划。
static void Main(string[] args)
{
double amount = 0;
int years = 0;
char menuItem;
Console.WriteLine("This program computes depreciation tables using various methods of depreciation");
menuItem = GetMenuChoice();
while (menuItem != 'Q')
{
ProcessMenuItem(menuItem,amount,years);
menuItem = GetMenuChoice();
}
Console.WriteLine("Goodbye!");
Console.ReadLine();
}
static void ProcessMenuItem(char menuItem, double amount, int years)
{
switch (menuItem)
{
case 'A':
ProcessSetValues(ref amount, ref years);
Console.WriteLine("{0} {1}", amount, years);
break;
case 'B':
StraightLineDepreciation( amount, years);
break;
case 'C':
break;
case 'D':
break;
}
}
static void ProcessSetValues(ref double amount, ref int years)
{
amount = GetPositiveDouble("How much money is to be depreciated?");
years = GetPositiveInteger("Over how many years");
return;
}
static void StraightLineDepreciation( double amount, int years)
{
if(amount != 0 && years != 0)
{
amount = amount / years;
Console.WriteLine("Year Depreciation");
Console.WriteLine("---- ---------------");
for (int counter = 0; counter < years; counter++)
{
Console.WriteLine(" {0,+6}{1}", amount, years);
}
}
else
{
Console.WriteLine("You have not entered any values for the amount and years.");
}
}
答案 0 :(得分:2)
你能否确保所有出现的方法都通过ref
,因为我认为这就是问题所在:
ProcessMenuItem(ref menuItem,ref amount,ref years);
StraightLineDepreciation( ref amount, ref years);
或者只是创建一个包装类并传递引用类型而不是使用值类型。
class DepreciationTracker
{
double amount;
int years;
}
ProcessMenuItem( DepreciationTracker obj)
{
//modify obj
}
StraightLineDepreciation( DepreciationTracker obj)
{
//modify obj
}
还会在Value vs Reference Types上推荐一本入门书。