gpt4 book ai didi

c# - 子列表项未在 C# 中显示

转载 作者:行者123 更新时间:2023-11-30 15:56:15 24 4
gpt4 key购买 nike

我正在尝试在列表中添加一个列表。但我无法从子列表中检索项目。没有错误,但没有从子列表中检索到数据。请关注 GenerateClue() 我认为错误就在那里。

当我尝试使用 clueList[0][0] 访问数据时,没有数据

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;

public class TrainingMode : MonoBehaviour {
private List<int> answerKey;
private List<int> clue;
private List<List<int>> clueList;
private int correct;
private int wellPlaced;
public Text answerKeyText;
System.Random random = new System.Random();

void Start () {
answerKey = new List<int>();
clue = new List<int>();
clueList = new List<List<int>>();

GenerateAnswerKey();
GenerateClue();

//CheckCorrectAndWellPlaced();

answerKeyText.GetComponent<Text>().text = answerKey[0] + " "+ answerKey[1] + " "+ answerKey[2];
foreach (List<int> arrClue in clueList)
{
foreach (int item in arrClue)
{
Debug.Log(item);
}
}
}

private void GenerateClue()
{

//Generate clue
for (int j = 0; j <= 5; j++)
{
for (int i = 0; i <= 2; i++)
{
int randomNumber = random.Next(0, 9);
if (clue.Contains(randomNumber))
{
i--;
}
else
{
clue.Add(randomNumber);
}

if (clue.Count == 3)
{
clueList.Add(clue);
clue.Clear();
}
}
}
}

private void CheckCorrectAndWellPlaced()
{
correct = 0;
wellPlaced = 0;
//Check for correct and wellplaced numbers
for (int i = 0; i <= 2; i++)
{
if (answerKey.Contains(clue[i]))
{
correct++;
}
if (clue[i] == answerKey[i])
{
wellPlaced++;
}
}
}

private void GenerateAnswerKey() {
//Generate answerkey
for (int i = 0; i <= 2; i++)
{
int randomNumber = random.Next(0, 9);
if (answerKey.Contains(randomNumber))
{
i--;
}
else
{
answerKey.Add(randomNumber);
}
}
}
}

最佳答案

问题是,当您将线索添加到线索列表时,它实际做的是传递一个引用,因为 List<> 是一个类。所以你最终只有 2 个变量指向同一个内存。一个是线索变量,另一个是线索列表[X]。因此,当您调用 clue.Clear() 时,您正在清除与 clueList[X] 实际上相同的内存的线索列表。

作为修复,只是改变这个:

if (clue.Count == 3)
{
clueList.Add(clue);
clue.Clear();
}

进入这个:

if (clue.Count == 3)
{
clueList.Add(new List<int>(clue));
clue.Clear();
}

关于c# - 子列表项未在 C# 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182998/

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