c# - 显示列表元素的方法
问题描述
我在课堂上有清单
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 作为方法吗?
解决方案
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
推荐阅读
- python - python selenium instagrambot - for i in range 循环(if 语句)
- javascript - 重定向到用户
- javascript - 如何根据条件执行 map.delete 方法(Javascript)
- node.js - MongoDB NodeJS - 如何获取两个日期之间的值总和?
- python - 你如何修复元素不可交互异常:python selenium
- jquery - 如何在 .xsl 文件中将参数传递给 $(document).ready()
- sql - 如何查找所有存在的事件并标记特定用户是否参加过?(PostgreSQL, Laravel)
- google-sheets - 过滤不在谷歌表格列表中的数据的功能是什么?
- apache-spark - 使用 pyspark 3.0.0 和 Hive 1.1.0 的 Hive 查询因“无法获取表 test_table。无效的方法名称:'get_table_req'”而失败
- regex - 带或不带破折号的正则表达式匹配校验和