c# - 无法访问列表 <> 中的列表 <>

标签 c#

泛型菜鸟努力访问列表中包含的类内的列表。基本上,我试图列出用户输入的人员的职业(我确信有一种更简单的方法可以做到这一点,但这段代码是为了练习泛型而编写的)。

类代码

namespace GenericPersonClass
{
class GenericPerson<T>
{
    static public List<T> Occupations = new List<T>();
    string name, famName;
    int age;

    public GenericPerson(string nameS,string famNameS,int ageI, T Note)
    {
        name = nameS;
        famName = famNameS;
        age = ageI;
        Occupations.Add(Note);
    }

    public override string  ToString()
        {

            return "The name is " + name + " " + famName + " and they are " + age;
        }
  }
}

主要代码

namespace GenericPersonClass
{
class Program
{
    static void Main(string[] args)
    {
        string token=null;
        string nameS, lastNameS,occS;
        int age;
        List<GenericPerson<string>> Workers = new List<GenericPerson<string>>();

        while (token != "no" || token != "No")
        {
            Console.WriteLine("Please enter the first name of the person to input");
            nameS = Console.ReadLine();
            Console.WriteLine("Please enter the last name of the person " + nameS);
            lastNameS = Console.ReadLine();
            Console.WriteLine("How old is " + nameS + " " + lastNameS);
            age = int.Parse(Console.ReadLine());
            Console.WriteLine("What is the occupation of " + nameS + " " + lastNameS);
            occS = Console.ReadLine();
            Console.WriteLine("Enter more data?...Yes/No");
            Workers.Add(new GenericPerson<string>(nameS, lastNameS, age, occS));
            token = Console.ReadLine();
        }

        Console.WriteLine("You provide the following employment...\n");
        for (int i = 0; i < Workers.Count; ++i)
        {
            Console.WriteLine("{0} \n", Workers[0].Occupations[i]); 
//This line above is shown as wrong by VS2010, and intellisense does not see Occupations...
        }

    }
}
}

感谢您的帮助, 狮子座

最佳答案

因此,您正在尝试从实例变量访问静态 List。这就是问题所在。您可以使用类而不是实例来直接访问它。

类似于:

GenericPerson<string>.Occupations[i]

它与列表没有任何关系 - 它与静态部分有关。

关于c# - 无法访问列表 <> 中的列表 <>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13215468/

相关文章:

c# - 执行 CompareFileAsync 时输出 "ChecksumNotSupported"FluentFTP

c# - Microsoft.Office.Interop.Excel.dll - 服务器未安装 Excel

c# - 以最大并发度运行多个操作 - 最后 2 个任务未执行

c# - 将 2 个连续字节转换为一个 int 值提高 C# 中的速度

c# - 将带有子查询的sql查询转换为linq语句

c# - 当子类不使用抽象类中的函数时,是否有使用 NotImplementedException 的替代方法?

c# - 使用 LinQ 将一系列值添加到列表中

c# - 为什么我的 ValidationMessageFor For TextArea 在页面加载时显示

c# - MongoDB:C# 还是 JavaScript?

c# - 将 tabitem 转换为窗口