0

问题是“重写 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???
        }
    }
4

3 回答 3

13

的覆盖ToString需要在Employee类型内部,而不是在类型外部。

public class Employee {
  ...
  public override string ToString() { 
    return String.Format("{0} {1} {2} {3}", _name, _number, _date, _salary);
  }
}

完成此操作后,任何调用都Employee::ToString将返回该格式化字符串而不是默认字符串

于 2013-08-13T17:02:17.897 回答
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
于 2013-08-13T17:05:51.990 回答
1

ToString() 方法可以返回单个字符串。

如果您明智地在单个字符串中返回所有数据成员,则需要对其进行格式化。

就像是:

public override string ToString()
{
    return(string.format("Name={0}, Number={1}...", _name, _number));
}
于 2013-08-13T17:05:53.473 回答