我想做的是让 UserID 根据类的类型生成随机值,userID 应该从 person.cs 生成。 例如,学生类生成一个学生 ID 和一个随机数,员工类应该生成一个员工 ID 和一个随机数,我遇到的问题是让任何用户 ID 样本数据显示在控制台输出中,我没有获得任何显示用户 ID 的数据,任何人都可以帮助我。
这是查看代码所需的链接
Person.cs
public class Person
{
static string title;
protected string firstName;
protected string lastName;
protected string address;
protected string gender;
protected string dateOfBirth;
protected string userID;
protected Random rnd = new Random();
// constructors
public Person()
{
}//end default constructor
public Person(string aTitle, string aFirstName, string aLastName, string aAddress,
string aGender, string aDateOfBirth)
{
title = aTitle;
firstName = aFirstName;
lastName = aLastName;
address = aAddress;
gender = aGender;
dateOfBirth = aDateOfBirth;
Console.WriteLine( this.DisplayInfo() );
//create userID
Console.WriteLine(userID);
this.DisplayInfo();
}//end 6-parameter constructor
刚刚添加
public string DisplayInfo()
{
return " You have created the person " + firstName + lastName +"\n whose address is" + address + "\n" + " whos is a " + gender + " and was born on " + dateOfBirth;
}//end method DisplayInfo
Staff.cs Student.cs 目前具有相同的数据
public class Staff : Person
{
public Staff(string aTitle, string aFirstName, string aLastName, string aAddress,
string aGender, string aDateOfBirth)
: base(aTitle, aFirstName, aLastName, aAddress,
aGender, aDateOfBirth)
{
this.userID = firstName.Substring(0, 1) + lastName.Substring(0, 5);
this.userID = this.userID + this.rnd.Next(1000, 9999);
}
PersonTest.cs
public class PersonTest
{
static void Main(string[] args)
{
Person testPerson = new Student("Mr.", "Merry ", "Lanes", " 493 Bluebane RD", "Male", " 8-06-1953 ");
Person studentPerson = new Person("Mr.", "Jerry ", "Panes", " 493 Bluebane RD", "Male", " 8-06-1953 ");
// THIS DATA SHOWS UP BUT NOT THE USERID
Console.ReadLine();
}//end main
最佳答案
您的用户 ID 为空。
在 Staff 类可以给 UserID 赋值之前,基类会尝试打印用户 ID
您的问题位于您编写“Create userID”的 person 类
如果您不熟悉继承过程,那么您就错过了关键步骤:
1:如果从子类调用父类构造函数,则所有父类都会在子类之前运行。
正如您所看到的,userID 将为空,如果您将 "create userID"
替换为 userID = "1000";
您应该会显示一些内容。
在我看来,你只需要改变你的算法,希望是一个简单的改变。
关于c# - 需要类(class)帮助吗?可能很简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3382816/