gpt4 book ai didi

c# - 无法访问 List<> 中的 List<>

转载 作者:行者123 更新时间:2023-11-30 22:23:47 25 4
gpt4 key购买 nike

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

类代码

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...
}

}
}
}

感谢您的帮助,狮子座

最佳答案

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

类似于:

GenericPerson<string>.Occupations[i]

它与 List 没有任何关系 - 它与 static 部分有关。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com