Skip to main content
 首页 » 编程设计

c#之类转换器

2024年02月20日12lautakyan007

我有以下类(class) 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 

?

提前致谢!

请您参考如下方法:

只需覆盖 ToString() 方法

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