类转换器

时间:2012-10-24 16:21:51

标签: c# class console tostring object-to-string

我有以下课程People

class People
{
    public enum Gender
    {
        Man = 'w',
        Woman = 'f'
    }

    public struct Person
    {
        public string First, Last;
        public Gender Gender;
        public int Age;
        public float Height, Weight;
    }

    public struct Group
    {
        public int Members;
        public string Name;
    }
}

现在,我们位于班级Program

class Program
{
    static void Main( string[] args )
    {
        People.Person p = new People.Person();

        p.First = "Victor";
        p.Last = "Barbu";
        p.Age = 14;
        p.Height = 175;
        p.Weight = 62;
        p.Gender = People.Gender.Man;

        Console.ReadLine();
    }
}

我想这样写一行:

Console.Write( x.toString() );

如何自定义x.toString()方法,以便在控制台中显示以下结果

Victor Barbu
14 years
Man
175 cm
62 kg

提前致谢!

3 个答案:

答案 0 :(得分:3)

过度使用ToString()方法

    public override string ToString()
    {
        // return the value you want here.
    }

答案 1 :(得分:1)

您想要覆盖Person类中的ToString方法。请参阅:http://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx

在你的情况下

public class Person
{
   // Snip
   public override string ToString()
   {
       return this.First + " " + this.Last; 
   }
}

如果你那么做

Console.WriteLine(person.ToString()); 

预期输出将是名字和姓氏,你可以明显地扩展它以包括你的其他字段和换行符等。

旁注;你正在做的是“漂亮的打印”我建议创建一个静态方法“公共静态字符串PrettyPrintPerson(Person p)”或类似的,来处理类的文本格式。

答案 2 :(得分:0)

class People 
{ 

    public override string ToString()
    {
        //This will return exactly what you just put down with line breaks
        // then just call person.ToString()
        return string.format("{1} {2}{0}{3} years{0}{4}{0}{5} cm{0}{6} kg", Environment.NewLine,
            First, Last, Age, Gender, Height, Weight);
    }
}