物品。不打印輸出位置的索引

[英]items.IndexOf not printing out position


I am fairly new to C# programming and have just finished learning about placeholders and the great convenience of the Array libraries/methods that can be used in C#.

我對c#編程相當陌生,剛剛學習了占位符以及可以在c#中使用的數組庫/方法的巨大便利。

I have written a very simple program that start with a populated array list of 3 strings. I have everything correct, as far as I know, but for whatever reason my items.IndexOf() method is only and always printing out 0 into the console.

我編寫了一個非常簡單的程序,它以一個包含3個字符串的填充數組列表開始。就我所知,我的一切都是正確的,但是無論出於什么原因,我的items.IndexOf()方法只是並且總是將0輸出到控制台。

Can anyone tell/teach me as to why this may be happening? As far as I know a foreach statement should update the values of the array so each pass through the items.IndexOf() value should change but it is not.

有人能告訴我為什么會發生這種事嗎?就我所知,foreach語句應該更新數組的值,以便每次通過items.IndexOf()值時都應該更改,但不是。

Here is my short code and I appreciate any advice, tips and help!

以下是我的簡短代碼,我非常感謝您的建議、建議和幫助!


namespace ConsoleApplication01
{
class Program
{
    static void Main(string[] args)
    {
        string[] items = { "sword", "shield", "potion" };

        WriteLine("Quick! You're being attacked by a Goblin Bruiser!");
        WriteLine("Which item will you use?");

        foreach (string item in items)
        {
            WriteLine("{0} {1}",items.IndexOf(item), item);
        }

        ReadLine();
    }
}
}

enter image description here

UPDATE: The issue was they syntax of items.IndexOf and Array.IndexOf. I assumed that because my items variable was an array it could be used in the way my code below shows. Thank you for all of the people who have taught me !

更新:問題是它們是項的語法。IndexOf和Array.IndexOf。我假設,因為我的items變量是一個數組,所以可以按照下面的代碼顯示的方式使用它。謝謝所有教過我的人!

1 个解决方案

#1


4  

you have your variables mixed up

把變量混合起來。

it should be items not item in the for loop. like this :

它應該是for循環中的項而不是項。是這樣的:

foreach (string item in items)
{
    WriteLine("{0} {1}", Array.IndexOf(items,item), item);
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/07/07/cbeca82b3c5e85efc26d6e15e1c0a4b2.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com