C#将xy坐标存储到Queue队列后无法正确打印的问题求助
问题原因
你调用Console.WriteLine(point)时,默认会调用int[]类型的ToString()方法,C#中数组类型没有重写该方法,只会输出System.Int32[]类型名,不会打印数组内部存储的坐标值。如果你的代码还存在编译报错的情况,是因为默认情况下WriteLine需要加Console.前缀,或者提前声明using static System.Console;。
解决方案
方案1:最小改动(无需修改存储逻辑)
直接在输出时访问数组的两个下标获取坐标值,修改循环内的输出代码即可:
public static void Main() { Random rnd = new Random(); Queue<int[]> myQ = new Queue<int[]>(); int plX = rnd.Next(0, 10); int plY = rnd.Next(0, 10); int[] arr1 = new int[] {plX, plY}; int[] arr2 = new int[] {plX, plY}; int[] arr3 = new int[] {plX, plY}; int[] arr4 = new int[] {plX, plY}; myQ.Enqueue(arr1); myQ.Enqueue(arr2); myQ.Enqueue(arr3); myQ.Enqueue(arr4); foreach (int[] point in myQ) { // 直接访问数组下标打印两个坐标值 Console.WriteLine($"X坐标:{point[0]},Y坐标:{point[1]}"); } }
方案2:更推荐的语义化实现
用自定义的坐标类型替代int[]存储坐标,避免下标访问错误,代码可读性更高,自带友好的序列化输出逻辑:
// 定义只读坐标值类型,语义更清晰 public readonly record struct Point(int X, int Y); public static void Main() { Random rnd = new Random(); Queue<Point> myQ = new Queue<Point>(); int plX = rnd.Next(0, 10); int plY = rnd.Next(0, 10); myQ.Enqueue(new Point(plX, plY)); myQ.Enqueue(new Point(plX, plY)); myQ.Enqueue(new Point(plX, plY)); myQ.Enqueue(new Point(plX, plY)); foreach (Point point in myQ) { Console.WriteLine(point); // 输出格式自动为 Point { X = xx, Y = xx } } }
内容的提问来源于stack exchange,提问作者LaTuor
相关产品推荐
相关产品推荐

