C# 使用方法Array.IndexOf()时遇到问题

C# 使用方法Array.IndexOf()时遇到问题,c#,C#,我是C新手,我尝试使用array.IndexOf查找特定数组的索引,但它总是将索引返回为-1。我的代码有什么问题吗 using System; using System.Collections.Generic; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string[] a = new string[]{ "a","b

我是C新手,我尝试使用array.IndexOf查找特定数组的索引,但它总是将索引返回为-1。我的代码有什么问题吗

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] a = new string[]{ "a","b","c","d" };
            int index = Array.IndexOf(a, "2");
            Console.WriteLine(index);
            Console.Read();

        }
    }
}

不,如果你知道你在做什么,你的代码没有问题

数组。IndexOfArray,对象

搜索指定对象并返回其在一维数组中第一次出现的索引

您试图在包含元素a、b、c、d的数组中搜索2。因为找不到,所以得到-1

搜索类似c的东西


大家好,欢迎来到Stack Overflow。我认为您对Array.IndexOf的作用和方式有点困惑。您正在包含字符串a、b、c、d的数组中搜索字符串2,您希望它返回什么?你能在这里详细说明你的期望吗-1表示未找到。试着搜索b,然后你应该回到1。回答你的问题,不,你的代码似乎没有问题。我想你期望它做一些其他的事情,尽管在这方面可能有一些错误。我猜你可能只是想要一个[1]索引-1意味着它不存在,因为2不在你的数组中,如果你搜索b,它将返回1I我现在得到了输出我正在尝试将索引作为参数而不是字符串给出,我的错误。谢谢你的帮助
int index = Array.IndexOf(a, "c"); // You will get 2 (which is the index)