首页 > 解决方案 > 类继承不打印任何东西

问题描述

我有一个问题,我继承了一个类来打印用户信息,但结果是什么,它只是打印空间名称和类名而已!!所以有人能在我之前请教我做错了什么吗!!它调试没有问题,但它只打印这个:

Program.Person !!!!!!!!!! 好的,我主要创建一个人,然后打印这个人

当我添加这两行时:

input.adjustAge(5); Console.WriteLine("用户名将他的年龄调整5:");

它只打印“”内的内容,但没有其他内容!?我很困惑..

这是我的 Person 类:

using System;
using System.Collections.Generic;
using System.Text;

namespace Program
{
    class Person
    {
        private string name;
        private string address;
        private double age;

        public Person()
        {
            this.name = " ";
            this.address = " ";
            this.age = 0.0;
        }
        //non/default constructor
        public Person(string name, string address, double age)
        {
            this.name = name;
            this.address = address;
            this.age = age;
            if (age < 0)
                age = 0.0;
        }
        
        public void setName (string name)
        {
            this.name = name;
        }
        public string getName()
        {
            return name;
        }
        public void setAddress(string address)
        {
            this.address = address;
        }
        public string getAddress()
        {
            return address;
        }

        public void setAge(double age)
        {
            this.age = age;
        }
        public double getAge()
        {
            return age;
        }

        public void adjustAge(double increment)
        {
            this.age = (this.age + increment);
        }
        

        public string toString()
        {
            string output = " ";
            output += "\nPersons Information: ";
            output += "\nPerson Name:  " + this.name;
            output += "\nPerson Address: " + this.address;
            output += "\nPerson Age: " + this.age;
            
            return output;
        }
    }
}

这是我的主要内容:

using System;

namespace Program
{
    class UsePerson
    {
        static void Main(string[] args)
        {
            Person input = new Person(" Sam ", " 419 West London Rd ", 30);
            Console.WriteLine(input);
        }
    }
}

标签: c#

解决方案


看起来你没有正确覆盖 ToString,

将您的 toString 更改为以下

public override string ToString()
{
   string output = " ";
     += "\nPersons Information: ";
   output += "\nPerson Name:  " + this.name;
   output += "\nPerson Address: " + this.address;
   output += "\nPerson Age: " + this.age;
        
   return output;
}

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method

我还建议您使用 C# Properties 而不是 getter 和 setter 方法。


推荐阅读