【问题标题】:C# Issues with variables displaying correct values with ToString/String.Format Method使用 ToString/String.Format 方法显示正确值的变量的 C# 问题
【发布时间】:2017-09-03 04:54:56
【问题描述】:

要求用户输入收入和支出,他们可以输入任意数量的每个。将有单独的 void 方法用于输入这些值,这些值将被发送到另一个类。总收入、总支出和总利润将使用 ToString/String.Format 方法显示。我试图让它工作,我已经切换了类、方法等的保护。我已经尝试了所有方法,但我无法使用 ToString 方法正确显示值。这些值显示为 $0.00。另外,我收到一条注释,上面写着 WriteLine(aIncomes.ToString()) 是对 ToString 的冗余调用,而 ToString 显示为灰色。如果我在 tostring 方法中写入变量,则会显示正确的值。所以我知道这个问题与对象实例没有正确传递到 tostring 方法有关。

任何 cmets、解释和/或解决方案将不胜感激。

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;
    }
}

【问题讨论】:

    标签: c# class variables methods tostring


    【解决方案1】:

    您的问题与ToString() 的调用方式完全无关。

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

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

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

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

    作为一般规则,使用属性方法(setter 或 getter)来维护与属性直接相关的状态以外的状态通常不是一个好主意。换句话说,您应该能够根据需要多次为属性赋值,并且除了立即更改 that 之外,对类有 no 影响适当的价值。如果您想对某事进行统计,那么最好使用常规命名方法。

    坦率地说,目前尚不清楚您对各种 Income 类字段表示的含义。在英语中,“所有公司收入”通常是“公司总收入”的同义词,您似乎在这里使用它们的同义词,这意味着您有两个字段,至少根据名称(虽然不是在实际使用中) 代表完全相同的事物。

    也不清楚为什么你有 companyIncome 字段(这只是最近的数据输入,看起来它可能只是一个局部变量),也不清楚为什么 companyProfit 字段是静态的(如果您有两个或更多 Income 课程,每个课程都针对不同的公司呢?)。

    上述所有“费用”成员和值都是如此。

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

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

    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;
        }
    }
    

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

    最后是这样的:

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

    代码编辑器是正确的。如果您将任何对象传递给Console.WriteLine(),它将自动调用ToString(),以便将对象转换为string 值以进行输出。您无需自己拨打ToString()

    【讨论】:

    • 非常感谢您的详细回复@Peter Duniho。我意识到我的问题是我从未在 ToString 方法中调用 Property() 方法。感谢您的解释和示例代码。我将留出一些时间更详细地查看您的帖子,以便进一步了解我正在努力解决的这些概念。一些代码被简单地删除了,所以我的代码对于任何查看它的人来说都更具可读性,我也应该删除对这些代码部分的任何引用。非常感谢您的回答,我非常感谢,并且知道您确实帮助了我。
    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 2023-02-23
    • 2016-06-06
    • 2017-09-08
    相关资源
    最近更新 更多