【问题标题】:how can I use the method 'IndexOf' in C#?如何在 C# 中使用方法 \'IndexOf\'?
【发布时间】:2023-01-22 17:27:36
【问题描述】:

我正在尝试在 LeetCode 上做搜索插入位置问题。我想在数组中搜索目标的索引。

这是我的代码:

public int SearchInsert(int[] nums, int target) {
    
    int index = nums.IndexOf(target);

    int ans = 0;

    Console.WriteLine(index);

    if (index == -1)
    {
        Array.Resize(ref nums, nums.Length + 1);
        nums[nums.Length - 1] = target;
        ans = nums.IndexOf(target);
    }

    return ans;
}

错误说:

错误 CS1501:方法“IndexOf”没有重载需要 1 个参数

【问题讨论】:

  • 该站点出于某种原因提供了您的问题的预览。请使用它,如果您的格式一团糟,请不要提交。
  • 这不是您应该问的问题。如果您阅读了相关文档,那么您就可以自己回答了。始终阅读相关文档。您可能是编程初学者,但 RTFM 是通用的。

标签: c# arrays indexing


【解决方案1】:

Array.IndexOf 是一个静态方法——你必须将数组本身作为第一个参数传递:

int index = Array.IndexOf(nums, target);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多