c# - 除了默认构造函数给出的内容之外,无法返回任何内容

标签 c# class methods constructor

我觉得我已经接近使用调试器了,但仍然无法弄清楚这一点。

我正在逐步执行以下代码

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””)。

回答您的问题:

How do I instantiate a class so I can use its methods without calling the default constructor?

正如其他人所指出的,您需要保留对新实例化的对象的引用,以便在从字段读取值时可以使用该实例。

考虑:

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 类的不同实例进行操作。。该不同的实例是由 new Rates(... 之一创建的GetRates 方法主体中的表达式。该实例具有您想要使用的速率,但它基本上被困在方法内。为什么会被困呢?因为您仅将实例分配给局部变量,并且局部变量在声明它们的方法之外无法访问。

有点像这样:而不是 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 实例。方法。

你写道:

My need for Rates myTax = new Rates(); in main is so that I can call the calculateTax method to do just that. If there is another way to call that method without calling the default constructor, I am all ears or fingers.

表达式new Rates()调用默认构造函数。那么,调用方式calculateTax不调用默认构造函数就是调用参数化构造函数:

Rates rates = new Rates(limit, lowRate, highRate);
double tax = rates.CalculateTax(taxpayer.Income);

您可能会说,“但我确实在 GetRates 方法中调用了参数化构造函数!”而且还存在给错误的汽车加注燃料的问题,因为 GetRates 方法中的 Rates 对象是一个不同的对象。您可以在不使用的对象上调用参数化构造函数,并在您使用的对象上调用默认构造函数。

关于c# - 除了默认构造函数给出的内容之外,无法返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135009/

相关文章:

具有静态类成员的 C++ 模板类

java - 方法返回 int 类型,但我不断收到 "this method must return a result of type int"错误

java - 如何在数据库中记录我的java程序流程?

c# - 使用官方 .NET SDK 在 Linux 上通过 cli 编译 C# 代码

没有嵌套在父类中的 C# 私有(private)类

c# - 如何使用 ASP.NET C# 设置 html 输入类型文本值?

python - 为什么我不能在类方法中使用 python 模块 concurrent.futures?

java - 在 Java 中创建一个类的实例?

java - 将 String obj 添加到列表中的列表中

c# - 最近有没有在 ScrollView 中移动 map (xamarin.forms.maps)的解决方案?