c# - 类继承不打印任何东西
问题描述
我有一个问题,我继承了一个类来打印用户信息,但结果是什么,它只是打印空间名称和类名而已!!所以有人能在我之前请教我做错了什么吗!!它调试没有问题,但它只打印这个:
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);
}
}
}
解决方案
看起来你没有正确覆盖 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;
}
我还建议您使用 C# Properties 而不是 getter 和 setter 方法。
推荐阅读
- python - 有没有办法下载 PoseNet 的冻结图(.pb 文件)?
- javascript - 使用 Slick Slide 触发按钮单击时的滑块不起作用?
- python - 加载 tkinter 应用程序后尝试启动另一个进程时出现 Python 错误
- android - 通过Sqlite在Android Studio中获取数据的静态方法错误
- javascript - 返回点数组中最近添加的点的颜色
- android - Android GridLayoutManager 一整行的背景图片
- node.js - 我如何添加除 multer-gridfs-storage 默认属性以外的新字段
- java - 是否可以扩展解决方案类?
- php - 排除 Woocommerce 类别
- r - 在另一个包中导入时,R 包数据不可用