C#如何获取数组指定位置值并解决Array类型索引器报错问题
报错根因
C#中的System.Array是所有数组类型的抽象基类,本身没有暴露公开的索引器供[下标]语法直接访问元素,因此对Array类型变量直接写arr[i]就会触发Cannot apply indexing with [] to an expression of type 'Array'编译错误。
修复方案
方案1:泛型数组参数(首选,类型安全无性能损耗)
将方法参数从非泛型的抽象Array改为泛型数组T[],泛型数组内置索引器语法,完全兼容原有调用逻辑:
static void SumOfOddsAndEvens<T>(T[] arr) where T : struct, IConvertible { int evenSum = 0; int oddSum = 0; for (int i = 0; i < arr.Length; i++) { int currentValue = Convert.ToInt32(arr[i]); Console.WriteLine(currentValue); // 按下标奇偶判断所属位置:i从0开始计数,0、2、4...为偶数位 if (i % 2 == 0) evenSum += currentValue; else oddSum += currentValue; } Console.WriteLine($"Sum of even slots: {evenSum}"); Console.WriteLine($"Sum of odd slots: {oddSum}"); }
原有调用代码无需任何修改,可直接正常运行:
static void Main(string[] args) { SumOfOddsAndEvens(new int[] { 1, 2, 3, 4, 6, 7, 8 }); }
方案2:保留抽象Array参数的兼容写法
如果业务场景必须使用抽象Array作为入参(比如需要兼容不同元素类型的数组传入),需要改用Array类提供的GetValue()方法按索引取值,不能直接用方括号索引:
static void SumOfOddsAndEvens(Array arr) { int evenSum = 0; int oddSum = 0; for (int i = 0; i < arr.Length; i++) { // 通过Array基类的GetValue方法获取指定索引的元素 int currentValue = Convert.ToInt32(arr.GetValue(i)); Console.WriteLine(currentValue); if (i % 2 == 0) evenSum += currentValue; else oddSum += currentValue; } Console.WriteLine($"Sum of even slots: {evenSum}"); Console.WriteLine($"Sum of odd slots: {oddSum}"); }
逻辑简化说明
原代码中额外维护isEven布尔变量切换状态的逻辑完全冗余,直接通过下标i的模2结果判断位置奇偶性即可,代码更简洁不易出错。
内容的提问来源于stack exchange,提问作者BobbyOrr4
相关产品推荐
相关产品推荐

