C#根据数组索引检查变量?
如果标题不够清楚,很抱歉,但这是我的问题 我有一个数组:C#根据数组索引检查变量?,c#,arrays,C#,Arrays,如果标题不够清楚,很抱歉,但这是我的问题 我有一个数组: public static string[] stringArray = new string[3] {"Menu", "Options", "Exit"}; 这个变量是: public static int pointerLocation = 0; 现在我的最终目标是检查指针位置是否等于数组的任何索引。 然后在“选定”项或当前索引前面打印> 我的问题是当我检查是否pointerLocation==stringArray[0]时,我当
public static string[] stringArray = new string[3] {"Menu", "Options", "Exit"};
这个变量是:
public static int pointerLocation = 0;
现在我的最终目标是检查指针位置是否等于数组的任何索引。
然后在“选定”项或当前索引前面打印>
我的问题是当我检查是否pointerLocation==stringArray[0]
时,我当然面临无法比较string和int的问题
那么我能做些什么来解决这个问题呢
编辑:
这正是我想要做的。
我正在尝试在控制台中创建一个菜单,我希望用户能够看到所选内容,因此它将如下所示:
> Start
Options
Exit
我希望>打印在lne上,其中数组中项的索引等于我的变量pointerLocation,如果这有意义的话
此外,当按下上/下箭头时,pointerLocation变量将递增/递减您可以在访问数组之前测试
pointerLocation
索引是否严格小于数组的大小:
if (pointerLocation < stringArray.Length)
{
// You can access and use the value at the specified index safely here
string value = stringArray[pointerLocation];
Console.WriteLine(value);
}
if(pointerLocation
我想这样做会有帮助
for (int i = 0; i < stringArray.Length; i++)
{
if (i == pointerLocation)
{
Console.WriteLine("> " + stringArray[pointerLocation]);
}
else
{
Console.WriteLine(stringArray[pointerLocation]);
}
}
for(int i=0;i”+stringArray[pointerLocation]);
}
其他的
{
Console.WriteLine(stringArray[pointerLocation]);
}
}
让我建议一些变量重命名
→ <代码>菜单项stringArray
→ <代码>所选pointerLocation
public static string[] stringArray = new string[3] {"Menu", "Options", "Exit"};
public static int pointerLocation = 0;
if(pointerLocation==Array.IndexOf(stringArray, "Menu"))
{
Console.WriteLine(stringArray[pointerLocation]);
}
但如果数组包含多个值,那么函数只返回匹配值的第一个索引。您实际上是想看看数组的索引0处是否有值?或者阵列是否有任何物品?@YuvalItzchakov我已经更新了我的帖子,以更好地展示我想要的东西。你的问题仍然毫无意义。听起来您实际上想将变量与
0
进行比较。试着写实际的代码,看看会发生什么。@SLaks显然我已经试过了。我想做的是:当用户按下eg时,我们在索引[0]处,当用户按下向上箭头时,我们转到[1],然后“>”从开始移动到选项。您如何绘制
?更新了OP以更好地解释它