执行foreach循环时输出System.Int32[],正确显示语法是什么?
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

