我有一个用于对象调用的类Person
。Person 类包含值 Name、Last_Name、Age 和最重要的 ID。
如何使用 ID 获取姓名或年龄等信息?代码:
// Person Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Person
{
private static int currentID;
protected int Age { get; set; }
protected string Name { get; set; }
protected string Name_Last { get; set; }
protected int ID { get; set; }
protected bool Teenager { get; set; }
public Person()
{
Name = "Default";
Name_Last = "Default";
ID = GetNextID();
Age = 0;
}
public Person(string name, int age)
{
this.Name = name;
this.Name_Last = Name_Last;
this.ID = GetNextID();
}
static Person()
{
currentID = 0;
}
protected int GetNextID()
{
return ++currentID;
}
public void Update(string name, int age, string LastName = "Default")
{
this.Name = name;
this.Name_Last = LastName;
this.Age = age;
}
public override string ToString()
{
return String.Format("Name: {0},"+getIsLastNameDiscription(" Lastname: ", ",")+" Age: {1}, isTeenager: "+isTeenager()+", CurrentID: {2}", this.Name, this.Age, this.ID);
}
private bool isLastname()
{
if (this.Name_Last != "Default")
return true;
else
return false;
}
private string getIsLastName()
{
if (this.isLastname())
return this.Name_Last;
else
return "";
}
private string getIsLastNameDiscription(string Stuffix = "", string EndStuffix = "")
{
if (this.isLastname())
return Stuffix+this.Name_Last+EndStuffix;
else
return "";
}
public string getIsTeenager(string TrueOutput = "true", string FalseOutput = "false")
{
if (this.isTeenager())
return TrueOutput;
else
return FalseOutput;
}
public bool isTeenager()
{
if(this.Age >= 13 && Age <= 18)
return true;
else
return false;
}
public string Discription()
{
return String.Format("{0} is {1} years old and he has the ID of {2}", this.Name,
this.Age,
this.ID);
}
}
// Program Class
class Program : Person
{
static void Main(string[] args)
{
Person Luke = new Person();
Luke.Update("Luke", 15);
Console.WriteLine(Luke.ToString());
Person Daniel = new Person();
Daniel.Update("Daniel", 14, "Jones");
Console.WriteLine(Daniel.ToString());
Person Aimee = new Person();
Aimee.Update("Aimee", 18, "Jones");
Console.WriteLine(Aimee.ToString());
Person Will = new Person();
Will.Update("William", 22, "Rae");
Console.WriteLine(Will.ToString());
Console.ReadLine();
}
}