如何&#34;问题&#34;在列表<questions>中与&#34; T&#34;相关联在List <t>?

时间:2016-07-19 03:24:42

标签: c# generics

我正在处理一个处理列表的应用程序。我有两个脚本;一个涉及特定班级的人;第二个涉及应用程序中的其他所有内容。这是一个真假游戏/应用程序,我通过在线教程学习。

第一个脚本是一个[System.Serializable]脚本,它只包含一个字符串和一个bool。这里的字符串是问题,bool验证了问题。主游戏控制器脚本在类中创建一个数组,它还包含一个未回答的问题列表,一旦提出问题就会定期更新。

我不太了解的代码行是

private static List<Questions> UnansweredQuestions;

哪里&#34;问题&#34;是包含问题和布尔的类。

<Questions>服务的确切功能是什么。我知道List<T>中的T指的是列表中元素的类型;通常是字符串或int。 T如何定义在这里?假设类Questions包含字符串和bool,它是否意味着创建的列表是字典?

4 个答案:

答案 0 :(得分:2)

不,List<Question>不是字典。它是List,包含Question s。

List<T>是通用的意味着它可以接受任何类型。编译器基本上从List获取代码,并将T的所有实例替换为Question,就像它已被专门写为Question类型的列表一样。

核心是List<T>将数组中的元素存储为private T[] _items。然后,只要空间不足,就会调整此数组的大小。

答案 1 :(得分:1)

让我们打破这个

private static List<Questions> UnansweredQuestions;

访问修饰符private表示UnansweredQuestions仅在其定义的类范围内可见。

关键字static表示您不需要您的课程实例。您的类的所有实例以及类中的其他静态属性/方法都可以看到相同的UnansweredQuestions

  

服务的确切功能。我知道列表中的T指的是列表中的元素类型;通常是字符串或int。

List<T>表示稍后要命名的类型的列表。当您编写List<Questions>时,您可以命名该类型。您告诉编译器您需要一个Questions对象列表。

  

鉴于课题包含字符串和bool,是否表示创建的列表是字典?

不,这真的是一个清单。如果列表中至少有一个对象,则可以执行类似

的操作
Questions firstQuestion = UnansweredQuestions[0];
if (firstQuestion.Answered == false) 
{
    Console.WriteLine(firstQuestion.Text);
}

这假设您的布尔值称为已回答,您的问题文本称为文本。

答案 2 :(得分:1)

参考:https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

将其视为多个T。与Array<T>类似。 T可以是任何类型:int,string,Question class等。例如:

Question question1 = new Question(); // only 1 question

List<Question> questions = new List<Question>(2);
questions.Add(new Question());  // 1st question added
questions.Add(new Question());  // 2nd question added

// access the second question by:
Question secondQuestion = questions[1];

答案 3 :(得分:0)

<T>object,它是所有内容的基础,就像这样List<System.Object>。当您声明List<string>时,它会使用类System.String创建一个列表。

此代码:private static List<Questions> UnansweredQuestions;,使用Question类创建列表。

所以这段代码:

private static List<Question> UnansweredQuestions = new List<Question>(10);

使用Question类创建10个长列表。这就像Array

private static Question[] UnansweredQuestions = new Question[10];

ListArray节省了空间和时间,因此您不必使用以下内容:

private static Question UnansweredQuestion1 = new Question();
private static Question UnansweredQuestion2 = new Question();
private static Question UnansweredQuestion3 = new Question();
private static Question UnansweredQuestion4 = new Question();
private static Question UnansweredQuestion5 = new Question();
private static Question UnansweredQuestion6 = new Question();
private static Question UnansweredQuestion7 = new Question();
private static Question UnansweredQuestion8 = new Question();
private static Question UnansweredQuestion9 = new Question();
private static Question UnansweredQuestion10 = new Question();

Plus ListArray允许编制索引,因此您可以获得此MyListOrArray[4]之类的项目。这将返回该索引处的项目。而在上面的示例中,有10个变量,您必须单独获取它们的值,例如UnansweredQuestion4