C#中Stack无法完整显示及输出类型名问题求助
问题分析与修复方案
核心问题梳理
- 程序提前终止,仅显示栈顶元素:原代码中
System.Environment.Exit(0);会在第一次循环执行后直接终止程序,导致仅处理栈顶的第一个元素,无法遍历剩余内容。 - 直接输出Stack显示类型名称:
Console.WriteLine(wordActions)调用的是Stack默认的ToString()方法,只会输出类型全称System.Collections.Generic.Stack1[System.String]`,而非栈内元素。 - 遍历期间修改集合触发异常:foreach是只读迭代器,遍历Stack时调用
Pop()修改集合,会抛出InvalidOperationException。 - 硬编码撤销动作文本:无论弹出哪个元素,都固定显示"CHANGED TEXT TO ITALIC TYPE",不符合动态逻辑。
- 逻辑运算符使用不当:判断输入时用了按位或
|,应使用逻辑短路或||(或统一转小写简化判断)。
修复后的完整代码
using System; using System.Collections.Generic; public class Program { public static void Main() { Stack<string> wordActions = new Stack<string>(); wordActions.Push("resized text to 100"); wordActions.Push("recoloured text to red"); wordActions.Push("changed font to Courier New"); wordActions.Push("aligned text to center"); wordActions.Push("changed text to italic type"); // 用while循环替代foreach,避免遍历修改集合的异常 while (wordActions.Count > 0) { string currentAction = wordActions.Peek(); Console.WriteLine($"当前最后操作:{currentAction}"); Console.WriteLine("是否要撤销最后一步操作?输入y确认,n跳过"); string userInput = Console.ReadLine()?.Trim().ToLower(); if (userInput == "y") { string undoneAction = wordActions.Pop(); Console.WriteLine($"已撤销操作:{undoneAction.ToUpper()}"); Console.WriteLine("当前剩余操作列表:"); PrintStack(wordActions); } else if (userInput == "n") { Console.WriteLine("操作列表保持不变:"); PrintStack(wordActions); } else { Console.WriteLine("输入无效,请输入y或n"); continue; } Console.WriteLine("是否继续操作?输入y继续,其他任意键退出"); string continueInput = Console.ReadLine()?.Trim().ToLower(); if (continueInput != "y") { break; } } Console.WriteLine("程序结束"); } // 封装打印Stack元素的方法 private static void PrintStack(Stack<string> stack) { foreach (string action in stack) { Console.WriteLine($" - {action}"); } } }
关键修改说明
- 替换循环类型:用
while循环替代foreach,既避免遍历期间修改集合的异常,又能通过Count属性控制循环持续条件。 - 新增打印方法:
PrintStack方法专门遍历并输出Stack内的所有元素,解决直接输出Stack显示类型名的问题。 - 动态获取撤销动作:通过
Pop()的返回值获取被撤销的操作,不再硬编码固定文本。 - 优化输入处理:将输入转为小写简化判断逻辑,增加输入无效的处理分支,同时添加继续操作的询问,让程序流程更合理。
- 移除强制退出:删除
System.Environment.Exit(0);,让程序可以正常循环或自然结束。
内容的提问来源于stack exchange,提问作者Dima
相关产品推荐
相关产品推荐

