2017-05-04 65 views
-1

雖然我正在打印值,但我沒有獲取值,而是打印類型。 在PlayerBOConsole.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); 
    } 
} 
+0

你不能這樣做。你必須遍歷數組來打印值。 –

+0

雖然你在'Player'項目上覆蓋了'ToString',但是這不會影響數組上的ToString的實現,這就是爲什麼你需要按照當前的答案建議並遍歷數組的方式來執行操作。 – Chris

+1

備註:將來只能發佈代碼的相關部分來重現問題,而不是完整的代碼轉儲,請參閱以下有關如何創建[MCVE]的內容。 – TheLethalCoder

回答

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; } 
+1

注意:雖然'\ n'很好,但我建議使用'Environment.NewLine'只是爲了好的做法。 – TheLethalCoder

+0

@TheLethalCoder - 邑:)同意你的看法。更正 –

+0

非常感謝...它工作正常 – Gayathri