2017-05-04 1 views
-1

値を印刷している間に値を取得できません。 で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); 
    } 
} 
+0

このようにすることはできません。あなたは値を出力するために配列を反復処理する必要があります。 –

+0

'ToString'をあなたの' Player'アイテムにオーバーライドしている間、これは配列に 'ToString'の実装に影響を与えません。なぜなら、現在の答えが示唆し、配列を反復する必要があるからです。 – Chris

+1

サイドノート:将来的には、完全なコードダンプではなく、問題の再現のためにコードのrelavent部分のみを投稿してください。以下の[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 - Yap :)あなたに同意します。訂正 –

+0

ありがとうたくさん...それはうまく動作します – Gayathri

関連する問題