You need to enable JavaScript to run this app. 如何将C#数组查找功能的普通代码封装为method/function方法
优惠活动
大模型
产品
解决方案
定价
更多

如何将C#数组查找功能的普通代码封装为method/function方法

数组搜索逻辑封装实现方案

以下是封装完成后的可运行完整代码:

class Program
{
    static void Main(string[] args)
    {
        int[] search = { 88, 62, 5, 18, 22, 78, 13, 8, 33, 7 };
        Console.WriteLine("Enter value to find");
        int val = int.Parse(Console.ReadLine());

        // 调用封装好的搜索方法
        int place = SearchValueInArray(search, val);

        if(place == -1)
        {
            Console.WriteLine("The Target Value was not found in the list");
        }
        else
        {
            Console.WriteLine("The Target Value was found at location: " + place);
        }
        Console.ReadLine();
    }

    // 独立封装的数组搜索方法
    /// <param name="searchArray">待搜索的int数组</param>
    /// <param name="targetValue">要查找的目标值</param>
    /// <returns>找到返回1-based位置,未找到返回-1</returns>
    static int SearchValueInArray(int[] searchArray, int targetValue)
    {
        for (int i = 0; i < searchArray.Length; i++)
        {
            if (searchArray[i] == targetValue)
            {
                // 原有逻辑返回1-based位置,如需0-based索引直接返回i即可
                return i + 1;
            }
        }
        // 遍历完未找到返回-1
        return -1;
    }
}

封装核心调整说明

  • 把原逻辑中固定的数组、固定长度10都替换为通用入参,方法可适配任意长度的int数组搜索,复用性更强
  • 搜索命中后直接return返回结果,不需要继续遍历剩余元素,性能优于原有遍历全量数组的逻辑
  • 方法标记为static,可直接在同类的静态Main方法中调用,不需要实例化Program类
  • 后续如果需要支持其他类型数组的搜索,可以将该方法改造为泛型方法,适配string、double等多种类型的匹配需求

内容的提问来源于stack exchange,提问作者Billionaire Blog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 17:18:03