C# · 12月 27, 2021

覆盖.ToString方法c#

好的,所以我写了一个C#编程书(我想在这里学习)的这个程序,它要求“覆盖ToString()方法返回所有的数据成员”.

我这样做是否正确?或者我刚刚成功编写了编译但不做任何事情的代码. ToString的目的是什么?

我花了约30分钟看着其他帖子,没有想到,所以我决定这样做.

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication297{class Program{ static void Main(string[] args) { String name = “Stormtrooper”; Employee s = new Employee(name); Console.WriteLine(“The type of hire is a {0}”,s.Name); Console.WriteLine(“The identification number is {0}”,s.Number); Console.WriteLine(“The date of hire is {0} ABY”,s.Date); Console.WriteLine(“The standard galactic salary is…{0:C}”,s.Salary); } class Employee { private string _name; private string _number; private int _date; private int _salary; public string Name { get { return _name; } } public string Number { get { return _number; } } public int Date { get { return _date; } } public int Salary { get { return _salary; } } public Employee(string n) { _name = n; _number = “AA23TK421”; _date = 4; _salary = 800; } } public override string ToString() { return “_name + _number + _date + _salary”.ToString(); }}}解决方法 你正在返回一个字符串,它只是说_name _number _date _salary.

你可能想要做的是使用这些字段构建一个字符串.如果你想让他们一起冲洗Concat会工作,但它将是非常不可读的

public override string ToString(){ return String.Concat(_name,_number,_date,_salary);}

然而,最好使用Format并包含具有值的标签

public override string ToString(){ return String.Format(“Name: {0},Number:{1},Date:{2},Salary:{3}”,_name,_salary);}