![](/img/trans.png)
[英]How to display the contents of a class which is generic list, by foreach loop?
[英]How to loop thru a Generic Class / List
嗨,我在这里通过 MSDN 学习泛型,我想做一个 foreach 循环以在 console.writeline 中显示数据。
我尝试按如下方式执行 foreach 循环,但它不起作用。
// Declare the generic class.
public class GenericList<T>
{
public void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int.
GenericList<int> list1 = new GenericList<int>();
list1.Add(150);
// Declare a list of type string.
GenericList<string> list2 = new GenericList<string>();
list2.Add("Toyota");
// Declare a list of type ExampleClass.
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
list3.Add(new ExampleClass());
}
}
foreach (GenericList<T> item in list2.ToString().ToList())
{
Console.WriteLine(item); // NOT WORKING !!!!
}
首先,通过在list2
上调用ToString()
方法,您将获得对象类型的名称,因为您没有创建自己的ToString()
方法实现。 因此,您正在尝试通过字符串“AppName.GenericList”的字母进行枚举。 不幸的是,字母是'char' 类型而不是GenericList。
其次,方法Add
后面没有后端 - 您要“添加”到列表中的项目,实际上并未添加到任何地方。 方法public void Add(T input) { }
什么都不做(你应该填写括号)。 此阶段的 GenericList 不存储任何数据。
第三,您无法通过 GenericList 进行枚举,因为您没有实现GetEnumerator
方法。 只有这样,您才能在您的类型的对象上使用关键字foreach
。
许多此类问题将在本教程结束时通过您提供的链接解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.