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