【问题标题】:How to loop thru a Generic Class / List如何通过通用类/列表循环
【发布时间】:2020-07-08 11:47:55
【问题描述】:

嗨,我正在通过 MSDN here 学习泛型 我想做一个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 !!!!
        }

【问题讨论】:

标签: c# .net


【解决方案1】:

首先,通过在list2 上调用方法ToString(),您将获得对象类型的名称,因为您没有创建自己的方法ToString() 的实现。因此,您正在尝试通过字符串“AppName.GenericList”的字母进行枚举。不幸的是,字母是 'char' 类型而不是 GenericList。

其次,方法Add 后面没有后端 - 您正在“添加”到列表中的项目,实际上并未添加到任何地方。方法public void Add(T input) { } 什么都不做(你应该填满括号)。此阶段的 GenericList 不存储任何数据。

第三,你不能枚举你的GenericList,因为你没有实现方法GetEnumerator。只有这样你才能在你的类型的对象上使用关键字foreach

在教程结束时,您提供的链接中的许多问题将得到解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多