c# - 限制数组大小 2D (C# UNITY)
问题描述
大家好,是否可以像这个例子一样限制数组大小
现在我只想展示其中的 6 个。
到目前为止我所做的是
自定义类
const int MAX = 104; // = 8 decks * 52 cards / 4cardsoneround
const int Y = 6;
int[,] arrayRoad = new int[Y, X];
public int[,] GetRoad(int x) {
arrayRoad = new int[x, 6];
return arrayRoad;
}
现在我像这样在我的MainClass上显示它
ScoreBoard bsb = new ScoreBoard();
private void Road()
{
bsb.makeRoad(history); // Road
int[,] arrayRoad = bsb.GetRoad(6); //<--- sample value 6
string s = "";
for (int y = 0; y < arrayRoad.GetLength(0); y++)
{
//just 27 for now
for (int x = 0; x < 28; x++)
{
s += string.Format("{0:D2}",arrayRoad[y, x]);
s += ".";
}
s += "\n";
}
Debug.Log(s);
}
这段代码的问题是它给了我一个Array out of index
这可能吗??
更新
public int[,] GetRoad(int x = MAX,int y = Y) {
arrayRoad = new int[y, x];
return arrayRoad;
}
在我Max = 104
和Y = 6
int[,] arrayRoad = bsb.GetRoad(12,6); //12 rows and 6 in height
string s = "";
for (int y = 0; y < arrayRoad.GetLength(0); y++)
{
for (int x = 0; x < arrayRoad.GetLength(1); x++)
{
s += string.Format("{0:D2}",arrayRoad[y, x]);
s += ".";
}
s += "\n";
}
Debug.Log(s);
}
在执行更新代码之前,我早先拥有所有这些值
现在,当我执行更新的代码时,这就是我得到的
预期的结果一定是这样
在那个黑色标记里面,只有那十二列必须显示,因为我在我的
int[,] arrayRoad = bsb.GetRoad(12,6);
解决方案
请注意:
public int[,] GetBigEyeRoad(int x) {
arrayRoad = new int[x, 6]; // <-------------
return arrayBigEyeRoad;
在那里,您将数组第二维的长度固定为 6。
for (int x = 0; x < 28; x++)
{
s += string.Format("{0:D2}",arrayBigEyeRoad[y, x]); // <------------
在那里,您尝试访问数组第二维上最多 28 个的索引。错误由此Out of Range
而来。
推荐阅读
- php - 如果没有找到文件,php glob 将值提高到 1
- ssh - Netmiko - Windows 10 - SSH 路由器 - 不能只运行第一个命令
- javascript - 如何在点击时附加 div?
- javascript - 如何通过组合组件进行条件渲染
- spring - 如何处理spring boot stomp websocket订阅端点以授权用户
- javascript - 我们如何仅从 localStorage 数组中删除一个值?
- .htaccess - htaccess rewriteCond 被忽略
- algorithm - 在无向加权图中找到“最公平”的交汇点
- sass - 将相同的样式应用于父级和嵌套的子级
- excel-formula - 有没有办法在不单独选择每一列的情况下在 Excel 中跨行相乘?