c# - 如何将 List.count 分配给变量?
问题描述
我试图总结 C# Unity 中两个列表的长度,但没有成功。整数变量“oneCount”和“twoCount”每次都返回 0,即使在增加列表大小之后也是如此。我确信有一个简单的解决方案,但我完全被卡住了。
我的代码如下所示:
public class list : MonoBehaviour
{
List<int> oneList = new List<int>();
List<int> twoList = new List<int>();
int oneCount;
int twoCount;
void Start()
{
oneCount = oneList.Count;
twoCount = twoList.Count;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
oneList.Add(1);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
twoList.Add(1);
}
if (Input.GetKeyDown(KeyCode.G))
{
Final();
}
void Final()
{
Debug.Log(oneCount + twoCount);
}
解决方案
调用会在调用.Count
时为您提供价值。
var list = new List<int>();
var c1 = list.Count; // c1 is 0
list.Add(1);
var c2 = list.Count; // c2 = 1, and c1 is still 0
在您的示例中,您似乎不需要oneCount
andtwoCount
变量:
void Final()
{
Debug.Log(oneList.Count + twoList.Count);
}
推荐阅读
- reactjs - 改为部署在子目录下/
- database - 分离 TFS 数据库时的后果和对用户的影响
- hibernate - 如何使用 JPARepository 仅返回目标实体
- c++ - 如何在右键单击时删除表格行
- ruby-on-rails - 将 paypal payflow 与 rails 集成
- javascript - 在移动设备上的图像之间滑动(左右)的最佳/最简单方法是什么?
- scala - 列表未在“foreach”语句中更新,返回空列表
- c# - 有没有办法通过脚本改变画布内元素的层顺序?
- xamarin - 在 Visual Studio 2019 for Mac 版本 8.2 之后无法构建
- reactjs - 在 Picker 元素中显示信息时出现问题