【发布时间】:2019-06-27 09:36:07
【问题描述】:
我正在尝试通过循环 x 次或直接添加 x nr 个元素来添加元素的非常量值。
我已经尝试循环 x 次并在每次迭代中添加一个元素,但最终只添加了一个元素。我也尝试添加一个集合,但结果相同。
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class tileMapDepth
{
public List<bool> tileMapWidth;
public tileMapDepth(List<bool> realWidth)
{
this.tileMapWidth = realWidth;
}
}
public class TestListTypeAndSuch : MonoBehaviour
{
public List<tileMapDepth> tileMap = new List<tileMapDepth>(1);
public int width = 5;
public int depth = 5;
void Start()
{
for (int i = 0; i < depth; i++)
{
tileMap.Add(new tileMapDepth(new List<bool>(new List<bool>(width))));
foreach (tileMapDepth tile in tileMap)
{
for (int j = 0; j < width; j++)
{
tile.tileMapWidth.Add(false);
}
}
}
}
}
预期的结果是将 nr 个元素添加到列表中,而不仅仅是一个元素。 当我尝试添加具有恒定值的布尔值作为数量时,它可以正常工作。但我需要用动态变量添加它。下面的代码是唯一有效的。
for (int i = 0; i < depth; i++)
{
tileMap.Add(new tileMapDepth(new List<bool>(new List<bool>(new bool[13]))));
}
【问题讨论】:
-
new List<bool>(new List<bool>(...))中的第一个列表是多余的。