0

我试图看看我是否可以使用 foreach 语句来尝试让我制作的程序搜索整个数组,因为我没有预设大小并且我不想为它玩猜谜游戏. 我尝试了这段代码,但它告诉我,“不能将类型'string'隐式转换为'int',它指向'if (query == search[k])

我不确定它到底在说什么,但有人可以帮忙吗?谢谢你。

    private void findLast_Click(object sender, EventArgs e)
    {
        query = textBox2.Text;
        search = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string k in search)
        {
            if (query == search[k])
            {
                MessageBox.Show("Match");
            }
            else
                MessageBox.Show("No Match");
        }
    }
4

4 回答 4

3

在每个循环中,您已经拥有该对象。

private void findLast_Click(object sender, EventArgs e)
    {
        query = textBox2.Text;
        search = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string k in search)
        {
            if (query == k)
            {
                MessageBox.Show("Match");
            }
            else
                MessageBox.Show("No Match");
        }
    }
于 2012-12-06T21:52:28.963 回答
2

k is a string - therefore you can't use it as the index of an array. Try just query == k instead.

于 2012-12-06T21:51:19.750 回答
1

Change your test to

if (query == k)

the syntax that you are using is for simple for loop

for(int k; k < search.Length; k++)
{
   if (query == search[k])
       .....
} 
于 2012-12-06T21:51:35.713 回答
1

C# 不是 JavaScript...foreach为您提供元素的价值,而不是索引:

 foreach (string currentItem in search)
 {
    if (query == currentItem)
    {...
于 2012-12-06T21:52:59.550 回答