首页 > 解决方案 > 显示列表元素的方法

问题描述

我在课堂上有清单

public List<Igrac> Igraci { get; set; } = new List<Igrac>();

班上:

class Igrac
{
    public string Ime { get; set; }
    public string Prezime { get; set; }
    public string Pozicija { get; set; }
    public int Godine { get; set; }
    public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
    {
        this.Ime = Ime;
        this.Prezime = Prezime;
        this.Pozicija = Pozicija;
        this.Godine = Godine;
    }
}

添加了新的列表元素:

noviklb.DodavanjeIgraca(new Igrac("Petar", "Petrovic", "Krilo", 1992));
noviklb.DodavanjeIgraca(new Igrac("Badr", "Hari", "Napad", 1993));

添加的方法工作正常。问题是,当我使用时Console.WriteLine,会出现这样的错误:

System.Collections.Generic.List`1[zadatak.Program+Igrac]

我用谷歌搜索,foreach 是解决方案,但我做错了。我需要写 foreach 作为方法吗?

标签: c#

解决方案


class Igrac
    {
        public string Ime { get;  }
        public string Prezime { get;  }
        public string Pozicija { get;  }
        public int Godine { get; }
        public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
        {
            this.Ime = Ime;
            this.Prezime = Prezime;
            this.Pozicija = Pozicija;
            this.Godine = Godine;
        }
    }

public override string ToString()
{
   return $"{Ime} {Prezime} {Pozicija} {Godine}";
} 

现在你可以使用了。

string myStringDate = new Igrac("Petar", "Petrovic", "Krilo", 1992).ToString();

另请注意:最好让您只获得属性。工作链接: https ://dotnetfiddle.net/zMNiln


推荐阅读