C#使用ToString / String.Format方法显示正确值的变量问题

时间:2017-04-07 17:53:25

标签: c# class variables methods tostring

要求用户输入收入和费用,他们可以按照自己的意愿输入尽可能多的收入和费用。存在用于输入这些值的单独void方法,这些方法将被发送到另一个类。使用ToString / String.Format方法显示总收入,总支出和总利润。我试图让它工作,我已经切换了类,方法等的保护。我已经尝试了一切,我无法使用ToString方法正确显示值。值显示为$ 0.00。另外,我得到一个说明,说WriteLine(aIncomes.ToString())是对ToString的冗余调用,而ToString是灰色的。如果我在tostring方法中执行变量的writelines,则会显示正确的值。所以我知道这个问题与没有正确传递给tostring方法的对象实例有关。

非常感谢任何评论,解释和/或解决方案。

public class MainClass
{
    public static Income aIncomes = new Income();


    public static void Main(string[] args)
    {
        Header();
        Directions();
        EnterIncome();
        EnterExpenses();

        WriteLine(aIncomes.ToString());
        Read();
    }

    public static void EnterIncome()
    {
        double companyIncome;
        double allCompanyIncome = 0;
        string inputValue;


        Write("Enter Income (enter value -99 to stop)  ");
        inputValue = ReadLine();

        while (inputValue != "-99")
        {
            if (double.TryParse(inputValue, out companyIncome) == false)
            {
                WriteLine("Invalid input - 0 stored in income");
            }
            else
            {
                aIncomes.companyIncome = double.Parse(inputValue);
                allCompanyIncome += aIncomes.companyIncome;
                aIncomes.allCompanyIncome = allCompanyIncome;
            }
            Write("Enter Income (Enter value -99 to stop)  ");
            inputValue = ReadLine();
        }
        //WriteLine(aIncomes.companyIncome);
        //WriteLine(aIncomes.allCompanyIncome);
    } 

    public static void EnterExpenses()
    {
        double companyExpenses;
        double allCompanyExpenses = 0;
        string inputValue;


        Write("Enter Expense (Enter value -99 to stop) ");
        inputValue = ReadLine();

        while (inputValue != "-99")
        {
            if (double.TryParse(inputValue, out companyExpenses) == false)
            {
                WriteLine("Invalid input - 0 stored in expenses");
            }
            else
            {
                aIncomes.companyExpenses = double.Parse(inputValue);
                allCompanyExpenses += aIncomes.companyExpenses;
                aIncomes.allCompanyExpenses = allCompanyExpenses;
            }
            Write("Enter Expense (Enter value -99 to stop) ");
            inputValue = ReadLine();
        }
        //WriteLine(aIncomes.companyExpenses);
        //WriteLine(aIncomes.allCompanyExpenses);
        //WriteLine(aIncomes.allCompanyIncome - aIncomes.allCompanyExpenses);
    }

    public static void MessageBox()
    {
        if (Income.companyProfit > 0)
        {
            System.Windows.Forms.MessageBox.Show("Westin made a profit", "Westin");
        }
        else if (Income.companyProfit <= 0)
        {
            System.Windows.Forms.MessageBox.Show("Westin had a loss", "Westin");
        }
    }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~

public class Income
{
    double companyTotalIncome;
    double companyTotalExpenses;
    public static double companyProfit;
    public double companyIncome;
    public double companyExpenses;
    public double allCompanyIncome;
    public double allCompanyExpenses;

    public Income()
    {

    }

    public Income(double ofAllCompanyIncome, double ofAllCompanyExpenses)
    {
        //companyIncome = ofCompanyIncome;
        //companyExpenses = ofCompanyExpenses;
        allCompanyIncome = ofAllCompanyIncome;
        allCompanyExpenses = ofAllCompanyExpenses;
    }

    public double AllCompanyIncome
    {
        set
        {
            allCompanyIncome = value;
            companyTotalIncome += allCompanyIncome;
        }
    }

    public double AllCompanyExpenses
    {
        set
        {
            allCompanyExpenses = value;
            companyTotalExpenses += allCompanyExpenses;
        }
    }

    public void Profit()
    {
        companyProfit = companyTotalIncome - companyTotalExpenses;

    }


    public override string ToString()
    {

        WriteLine(allCompanyIncome);
        WriteLine(allCompanyExpenses);
        string str = string.Empty;
        str += string.Format("Total Income  {0:C} \n", companyTotalIncome);
        str += string.Format("Total Expenses {0:C} \n", companyTotalExpenses);
        str += string.Format("Profit      {0:C}", companyProfit);  
        return str;
    }
}

1 个答案:

答案 0 :(得分:1)

你的问题与调用ToString()的方式毫无关系。

用户输入后,你有这样的代码:

aIncomes.companyIncome = double.Parse(inputValue);
allCompanyIncome += aIncomes.companyIncome;
aIncomes.allCompanyIncome = allCompanyIncome;

在这里,您直接访问类的字段,而不是使用名为AllCompanyIncome的属性。该属性设置器是唯一可以修改字段companyTotalIncome的地方。由于您从未执行过修改该字段的代码,因此它仍然设置为默认值0

您似乎尝试添加一些诊断代码(可能还有字段?)以尝试调试问题,但这些字段未连接到您实际遇到问题的字段。因此,虽然它们看似正确,但它们并没有告诉您有关您遇到问题的字段。

作为一般规则,使用属性方法(setter或getter)来维护除与属性直接相关的状态之外的状态通常不是一个好主意。换句话说,您应该能够根据需要多次为属性分配值,并且除了的立即更改之外,对该类具有 no 效果适当的价值。如果你想保持某个东西的运行记录,那么最好为此目的使用常规的命名方法。

坦率地说,您不清楚各种Income类字段的含义是什么意思。在英语中,“所有公司收入”通常与“公司总收入”同义,并且您似乎在这里同义地使用它们,这意味着您有两个字段,至少根据名称(尽管不是在实际使用中) )代表同样的事情。

还不清楚为什么你有companyIncome字段(这只是最新的数据输入,看起来它可能只是一个局部变量),也不是{{1} } field是静态的(如果你有两个或更多companyProfit个类,每个类都用于不同的公司怎么办?)。

同样的所有上述“费用”成员和价值观。

一般来说,你应该完全避开公共领域。如果需要访问存储在字段中的值,请声明可以返回该值的属性。不要使用属性设置器(或getter)来修改不直接属于该属性状态的任何内容。不要使用Income成员来存储每个实例的值。如果您已经解析了一个值,请不要浪费时间再次解析它。只需使用您已经成功解析的值。

记住这些事情,这里更接近我编写代码的方式:

static

我注释掉了你没有提供实现的方法,并删除了其他注释掉和未使用的代码。

最后,这个:

  

另外,我得到一条说明WriteLine(aIncomes.ToString())是对ToString的冗余调用,而ToString是灰色的。

代码编辑器是正确的。如果您将任何对象传递给class Program { public static Income aIncomes = new Income(); public static void Main(string[] args) { //Header(); //Directions(); EnterIncome(); EnterExpenses(); Console.WriteLine(aIncomes.ToString()); Read(); } public static void EnterIncome() { double companyIncome; string inputValue; Write("Enter Income (enter value -99 to stop) "); inputValue = ReadLine(); while (inputValue != "-99") { if (double.TryParse(inputValue, out companyIncome) == false) { WriteLine("Invalid input - 0 stored in income"); } else { aIncomes.AddCompanyIncome(companyIncome); } Write("Enter Income (Enter value -99 to stop) "); inputValue = ReadLine(); } } public static void EnterExpenses() { double companyExpenses; string inputValue; Write("Enter Expense (Enter value -99 to stop) "); inputValue = ReadLine(); while (inputValue != "-99") { if (double.TryParse(inputValue, out companyExpenses) == false) { WriteLine("Invalid input - 0 stored in expenses"); } else { aIncomes.AddCompanyExpenses(companyExpenses); } Write("Enter Expense (Enter value -99 to stop) "); inputValue = ReadLine(); } } } class Income { double companyTotalIncome; double companyTotalExpenses; public Income() { } public Income(double ofAllCompanyIncome, double ofAllCompanyExpenses) { companyTotalIncome = ofAllCompanyIncome; companyTotalExpenses = ofAllCompanyExpenses; } public void AddCompanyIncome(double value) { companyTotalIncome += value; } public void AddCompanyExpenses(double value) { companyTotalExpenses += value; } public double Profit { get { return TotalIncome - TotalExpenses; } } public double TotalIncome { get { return companyTotalIncome; } } public double TotalExpenses { get { return companyTotalExpenses; } } public override string ToString() { string str = string.Empty; str += string.Format("Total Income {0:C} \n", TotalIncome); str += string.Format("Total Expenses {0:C} \n", TotalExpenses); str += string.Format("Profit {0:C}", Profit); return str; } } ,它将自动调用Console.WriteLine()以将对象转换为ToString()值以进行输出。您无需亲自致电string