嘗試覆蓋ToString()並使用GetType()返回正在使用的對象的類型。它正在返回信息,但它包含NameSpace。問題是如何剝離NameSpace並僅顯示對象名稱。這裏是我的代碼:Object.GetType()也返回項目名稱
namespace Trial
{
class Testing
{
static void Main(string[] args)
{
//Variables
Person[] objectPerson = new Person[5]; //create an array of references
objectPerson[0] = new Person(10, "John", 35, 1200.00);
objectPerson[1] = new Person(20, "Jill", 30, 2400.00);
objectPerson[2] = new Person(30, "Joann", 40, 600.00);
objectPerson[3] = new Person(40, "Jimmy", 25, 4800.00);
objectPerson[4] = new Person(50, "Jamie", 45, 300.00);
for (int y = 0; y < objectPerson.Length; ++y)
{
Console.WriteLine(objectPerson[y].ToString());
}
Console.Write("\nPress any key to exit . . .");
Console.ReadKey();
}
}
class Person
{
//Data fields
private int number;
private string name;
private int age;
private double amountDue;
//Constructors
public Person(): this(9,"ZZZ",0,0.00)
{
}
public Person(int _Number, string _Name, int _Age, double _AmountDue)
{
Number = _Number;
Name = _Name;
Age = _Age;
AmountDue = _AmountDue;
}
//Properties
public int Number
{
get { return number; }
set { number = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public double AmountDue
{
get { return amountDue; }
set { amountDue = value; }
}
//Overrides
public override string ToString()
{
return(this.GetType() + ": " + this.Number + " - " + this.Name + " (" + this.Age.ToString() + "yo) | The total annual ammount is: " + this.AmountDue.ToString("C") + " and the quarterly payment is " + (this.AmountDue/4).ToString("C"));
}
}
}
你可以使用'nameof(Person)'。 –