2
泛型新手努力訪問包含在列表中的類內的列表。基本上我試圖列出用戶輸入的人的職業(我相信有這樣做的更簡單的方法,但是這個代碼是用來練習泛型的)。無法訪問List <>內的列表<>
類代碼
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...
}
}
}
}
感謝您的幫助, 利奧
職業在Generic person類中被列爲靜態,所以它不是可以在實例上訪問的成員變量。這樣做是令人困惑的,但我不知道你在做什麼,所以提供有意義的建議並不容易。你可以使用'GenericPerson.Occupations'訪問職業,但我不知道它是否按照你的意圖工作。 –