问题是“覆盖ToString()方法以返回所有数据成员。
当我返回_name时,会给出我在当前上下文中不存在的错误。我不明白这应该如何返回所有数据成员
sing 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 HOW DO I RETURN THIS???
}
}
答案 0 :(得分:13)
ToString
的覆盖需要在Employee
类型内,而不是在public class Employee {
...
public override string ToString() {
return String.Format("{0} {1} {2} {3}", _name, _number, _date, _salary);
}
}
类型之外。
Employee::ToString
完成此操作后,对{{1}}的任何调用都将返回该格式化字符串,而不是默认字符串
答案 1 :(得分:1)
您的ToString()方法不在您的Employee类中。它需要在Employee构造函数之后的第二个右括号之前向上移动。换句话说:
public Employee(string n)
{
_name = n;
_number = "AA23TK421";
_date = 4;
_salary = 800;
}
//} remove this end brace
public override string ToString()
{
return _name; // or whatever you want the result to be
}
} // brace moved to here
答案 2 :(得分:1)
ToString()方法可以返回单个字符串。
如果您明智地将所有数据成员返回到单个字符串中,则需要对其进行格式化。
类似的东西:
public override string ToString()
{
return(string.format("Name={0}, Number={1}...", _name, _number));
}