You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行foreach循环时输出System.Int32[],正确显示语法是什么?

解决foreach遍历数组输出异常的问题

Hey there! I see exactly where the issue is in your code. When using the foreach loop, you’re printing the entire array myArray instead of the individual element you’re currently iterating over—that’s why you’re getting System.Int32[] as output. This is just the default string representation of an integer array in C#, not the actual element values.

错误原因拆解

Look at your current foreach block:

foreach (int j in myArray)
{
    Console.WriteLine("o/p" + myArray);
}

You’re referencing the whole array myArray directly here. Since C# arrays don’t override the ToString() method, it just returns the type name instead of the elements inside.

修正后的代码

Instead, you need to use the loop variable j—this variable holds the current element from the array during each iteration. Here’s the fixed version:

using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] myArray = new int[3];
            for (int i = 0; i < 3; i++)
            {
                myArray[i] = Convert.ToInt32(Console.ReadLine());
            }
            foreach (int j in myArray)
            {
                // Use the loop variable j to access the current element
                Console.WriteLine("o/p: " + j);
            }
            Console.ReadLine();
        }
    }
}

(I removed the unused System.Collections namespace to clean up the code a little.)

额外小技巧

If you want to print all elements in a single line (instead of each on a new line), you can use string.Join for a cleaner output:

Console.WriteLine("All elements: " + string.Join(", ", myArray));

This would give you something like All elements: 5, 10, 15 if those are the values you entered.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:43:10