当我打印值时,我没有获得价值而是打印类型。
在PlayerBO
班Console.WriteLine(playerList);
打印player[]
但我需要打印价值。
我的代码出了什么问题?
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);
}
}
答案 0 :(得分:3)
Console.WriteLine(playerList)
将执行为数组实现的ToString
- 这与覆盖该数组中对象类型的ToString
不同。
要打印数组中的值,需要迭代它:
foreach(var item in playerList)
{
Console.WriteLine(item);
}
或者另一种方法是使用string.Join
:
Console.WriteLine(string.Join(Environment.NewLine, playerList));
另外,请看一下自动属性:
//Instead of this:
public string Name
{
get { return this._name; }
set { this._name = value; }
}
//You can do this:
public string Name { get; set; }