[英]Override ToString() method with List<>
What I have tried so far: 到目前为止我尝试过的是:
private List<Item> item = new List<Item>();
public List<Item> Item { get; set; } //Provide Access to List item
public Inventory() // Default constructor made to initialize default List<> value
{
Item = new List<Item>()
{
new Item("iPod"),
new Item("Samsung"),
new Item("Motorolla"),
new Item("Nokia")
};
}
override String ToString() {
return ...?
}
How do I implement an override ToString() method in my class that returns the default List<> values to the user 如何在我的类中实现重写ToString()方法,该方法将默认List <>值返回给用户
Thanks, appreciate it. 谢谢,谢谢。
Since you state that you've already overrided the ToString()
method for individual list items, you can do something like this: 由于您声明已经为单个列表项覆盖了
ToString()
方法,因此可以执行以下操作:
public override string ToString()
{
return string.Join(", ", item);
}
So, assuming your Item's ToString() method just returns the string you pass in to create it, you would end up with a string like this: iPod, Samsung, Motorola, Nokia
. 因此,假设您Item的ToString()方法仅返回您传递来创建它的字符串,那么最终将得到如下字符串:
iPod, Samsung, Motorola, Nokia
。
If your list is likely to grow to a large amount, and you just want a preview, you could take the first 5 items to build the string from like so: 如果您的列表可能会大量增加,而您只想预览,则可以采用前5个项来构建字符串,如下所示:
public override string ToString()
{
return string.Join(", ", item.Take(5));
}
By the way, I'd recommend calling your Item
property Items
since it is a collection and not a single item. 顺便说一句,由于它是一个集合而不是单个项目,因此建议您将
Item
属性称为Items
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.