雖然我正在打印值,但我沒有獲取值,而是打印類型。 在PlayerBO
類Console.WriteLine(playerList);
打印player[]
但我需要打印值。覆蓋ToString但打印數組時顯示類型
我的代碼有什麼問題?
public class Program
{
public static void Main(string[] args)
{
Player[] p= new Player[100];
Console.WriteLine("Enter the number of players");
int n = int.Parse(Console.ReadLine());
int i;
for (i = 0; i < n; i++)
{
p[i] = new Player();
Console.WriteLine("Enter the player name");
p[i].Name = Console.ReadLine();
Console.WriteLine("Enter the country name");
p[i].Country = Console.ReadLine();
Console.WriteLine("Enter the skill");
p[i].Skill = Console.ReadLine();
}
PlayerBO pb=new PlayerBO();
pb.DisplayPlayerDetails(p);
}
}
public class Player
{
private string _country;
private string _skill;
private string _name;
public Player(string _name, string _country, string _skill)
{
this._name = _name;
this._country = _country;
this._skill = _skill;
}
public Player() { }
public string Name
{
get { return this._name; }
set { this._name = value; }
}
public string Country
{
get { return this._country; }
set { this._country = value; }
}
public string Skill
{
get { return this._skill; }
set { this._skill = value; }
}
public override string ToString()
{
return string.Format("{0,-20}{1,-20}{2,0}", Name, Country, Skill);
}
}
public class PlayerBO
{
public void DisplayPlayerDetails(Player[] playerList)
{
playerList = new Player[100];
Console.WriteLine("Player Details");
Console.WriteLine(playerList);
}
}
你不能這樣做。你必須遍歷數組來打印值。 –
雖然你在'Player'項目上覆蓋了'ToString',但是這不會影響數組上的ToString的實現,這就是爲什麼你需要按照當前的答案建議並遍歷數組的方式來執行操作。 – Chris
備註:將來只能發佈代碼的相關部分來重現問題,而不是完整的代碼轉儲,請參閱以下有關如何創建[MCVE]的內容。 – TheLethalCoder