我觉得我正在接近使用调试器,但仍然无法弄清楚这一点。
我正在遍历以下代码
namespace Taxes
{
public class Rates
{
//A class constructor that assigns default values
public Rates()
{
incLimit = 30000;
lowTaxRate = .15;
highTaxRate = .28;
}
//A class constructor that takes three parameters to assign input values for limit, low rate and high rate.
public Rates(int lim, double low, double high)
{
incLimit = lim;
lowTaxRate = low;
highTaxRate = high;
}
// A CalculateTax method that takes an income parameter and computes the tax as follows:
public int CalculateTax(int income)
{
//determine if the income is above or below the limit and calculate the tax owed based on the correct rate
int taxOwed;
if (income < incLimit)
taxOwed = Convert.ToInt32(income * lowTaxRate);
else
taxOwed = Convert.ToInt32(income * highTaxRate);
return taxOwed;
}
}
// The Taxpayer class is a comparable class
public class Taxpayer : IComparable
{
//Use get and set accessors.
private int taxOwed;
string SSN
{ set; get; }
int grossIncome
{ set; get; }
int TaxOwed {
get
{
return taxOwed;
}
}
int IComparable.CompareTo(Object o)
{
int returnVal;
Taxpayer temp = (Taxpayer)o;
if (this.taxOwed > temp.taxOwed)
returnVal = 1;
else if (this.taxOwed < temp.taxOwed)
returnVal = -1;
else returnVal = 0;
return returnVal;
}
public static Rates GetRates()
{
// Local method data members for income limit, low rate and high rate.
int incLimit;
double lowRate;
double highRate;
string userInput;
//Rates myRates = new Rates(incLimit, lowRate, highRate);
//Rates rates = new Rates();
// Prompt the user to enter a selection for either default settings or user input of settings.
Console.Write("Would you like the default values (D) or would you like to enter the values (E)?: ");
// if they want the default values or enter their own
userInput = (Console.ReadLine());
if (userInput == "D" || userInput == "d")
{
Rates myRates = new Rates();
return myRates;
//Rates.Rates();
//rates.CalculateTax(incLimit);
}
else if (userInput == "E" || userInput == "e")
{
Console.Write("Please enter the income limit: ");
incLimit = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the low rate: ");
lowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the high rate: ");
highRate = Convert.ToDouble(Console.ReadLine());
Rates myRates = new Rates(incLimit, lowRate, highRate);
return myRates;
//rates.CalculateTax(incLimit);
}
else return null;
}
static void Main(string[] args)
{
Taxpayer[] taxArray = new Taxpayer[5];
//Rates taxRates = new Rates();
// Implement a for-loop that will prompt the user to enter the Social Security Number and gross income.
for (int x = 0; x < taxArray.Length; ++x)
{
taxArray[x] = new Taxpayer();
Console.Write("Please enter the Social Security Number for taxpayer {0}: ", x + 1);
taxArray[x].SSN = Console.ReadLine();
Console.Write("Please enter the gross income for taxpayer {0}: ", x + 1);
taxArray[x].grossIncome = Convert.ToInt32(Console.ReadLine());
//taxArray[x].taxOwed = taxRates.CalculateTax(taxArray[x].grossIncome);
}
Rates myRate = Taxpayer.GetRates();
//Taxpayer.GetRates();
// Implement a for-loop that will display each object as formatted taxpayer SSN, income and calculated tax.
for (int i = 0; i < taxArray.Length; ++i)
{
Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, myRate.CalculateTax(taxArray[i].grossIncome));//taxArray[i].taxOwed);
}
// Implement a for-loop that will sort the five objects in order by the amount of tax owed
Array.Sort(taxArray);
Console.WriteLine("Sorted by tax owed");
for (int i = 0; i < taxArray.Length; ++i)
{
//double taxes = myTax.CalculateTax(taxArray[i].grossIncome);
Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, myRate.CalculateTax(taxArray[i].grossIncome));
}
}
}
}
我已经解决了所有问题,但出于某种原因,现在排序不是按欠税额排序。
最佳答案
除了Taxpayer.GetRates()
之外:纳税人类别不应该负责确定税率。如果纳税人可以确定税率,则税率很可能为零。将其移至Rates
类可能更有意义。
这个问题的答案显示了一个示例,该示例应该可以帮助您了解错误的出处。如果您想要与您的代码有关的特定建议,请发布完整的编译程序。您发布的示例代码无法编译(错误:“名称'taxRates'在当前上下文中不存在”)。
要回答您的问题:
我如何实例化一个类,以便可以使用其方法而无需调用默认构造函数?
就像其他人指出的那样,您需要保留对新实例化对象的引用,因此当您从字段中读取值时可以使用该实例。
考虑:
void SetRates()
{
Rates rates = new Rates(10000, 0.3, 0.4);
}
void UseRates(Taxpayer taxpayer)
{
taxpayer.Tax = new Rates().CalculateTax(taxpayer.Income);
}
void Main()
{
SetRates(); // creates an object and throws it away
Taxpayer taxpayer = new Taxpayer(20000);
UseRates(taxpayer); // creates a new object with default values
Console.WriteLine(taxpayer.Tax);
}
相反,返回在SetRates()中创建的对象(并改名为GetRates())。然后将其传递给UseRates方法:
Rates GetRates()
{
return new Rates(10000, 0.3, 0.4);
}
void UseRates(Taxpayer taxpayer, Rates rates)
{
taxpayer.Tax = rates.CalculateTax(taxpayer.Income);
}
void Main()
{
Rates rates = GetRates();
Taxpayer taxpayer = new Taxpayer(20000);
UseRates(taxpayer, rates);
Console.WriteLine(taxpayer.Tax);
}
关于修改后的代码,
Rates myTax = new Rates();
Taxpayer.GetRates();
现在,
Taxpayer.GetRates()
将一些值分配给Rates实例,但它与使用语句Rates myTax = new Rates()
创建的Rates实例不同。语句Rates myTax = new Rates()
调用默认的Rates构造函数,这就是您稍后在计算税金的方法中使用的实例!这解释了为什么总是使用默认值来计算您的税金。GetRates方法对Rates类的另一个实例进行操作。该不同的实例由GetRates方法主体中的
new Rates(...
表达式之一创建。该实例具有您要使用的费率,但是它基本上被困在方法中。为什么会被困住?因为仅将实例分配给局部变量,并且在声明局部变量的方法之外无法访问局部变量。有点像这样:我们有
Rates
而不是Car
,而我们有GetRates
而不是FillFuelTank
。然后,您的代码将执行以下操作:Get a new car //Rates myTax = new Rates();
Go to the gas station //Taxpayer.GetRates();
现在,GetRates()方法...我的意思是,FillFuelTank方法...执行此操作:
Get a new car with fuel in it //Rates myRates = new Rates(incLimit, lowRate, highRate)
你看到你做了什么?您已经开车到新车的加油站,里面有第二辆加油的汽车,然后又回到第一辆车开走了-没有加任何燃料。
一种解决方案是将
myTax
作为参数传递给GetRates()
方法。更好的解决方案是从GetRates()
方法返回Rates实例。你写了:
我需要的费率myTax = new Rates();总的来说,这样我就可以调用calculateTax方法来做到这一点。如果有另一种方法可以调用该方法而无需调用默认构造函数,那我真是无所适从。
表达式
new Rates()
调用默认构造函数。因此,不调用默认构造函数而调用calculateTax
的方法是调用参数化构造函数:Rates rates = new Rates(limit, lowRate, highRate);
double tax = rates.CalculateTax(taxpayer.Income);
您可能会说:“但是我确实在GetRates方法中调用了参数化构造函数!”还有一个问题,就是用错误的汽车加油,因为GetRates方法中的Rates对象是一个不同的对象。您在不使用的对象上调用参数化的构造函数,并在您使用的对象上调用默认的构造函数。