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

运行程序时如何修改终端外观并实现C#列表逐行打印?

解决C#终端逐行打印及外观修改问题

一、实现逐行打印员工姓名

你的代码里使用Console.Write()会将内容连续输出在同一行,要实现逐行打印,有几种简单方案:

1. 替换为Console.WriteLine()

Console.WriteLine()会自动在输出内容末尾添加换行符,直接修改循环内的代码即可:

List<string> employees = new List<string>() { "adam", "amy" };
employees.Add("barbara");
employees.Add("barbara");

for (int i = 0; i < employees.Count; i++)
{
    Console.WriteLine(employees[i]);
}

2. 手动添加换行符

如果坚持用Console.Write(),可以在每个姓名后拼接换行符:

// 通用换行符\n
Console.Write(employees[i] + "\n");
// 适配不同系统的换行(Windows用\r\n,Linux用\n)
Console.Write(employees[i] + Environment.NewLine);

3. 更简洁的foreach遍历

遍历列表时用foreach循环更直观,代码更简洁:

List<string> employees = new List<string>() { "adam", "amy" };
employees.Add("barbara");
employees.Add("barbara");

foreach (string employee in employees)
{
    Console.WriteLine(employee);
}

二、修改终端外观

除了换行,你还可以通过C#的Console类直接调整终端的显示效果:

  • 修改文字颜色:Console.ForegroundColor = ConsoleColor.Blue;(可选颜色包括Red、Green、Yellow等)
  • 修改背景颜色:Console.BackgroundColor = ConsoleColor.Gray;
  • 重置颜色:Console.ResetColor();(恢复终端默认配色)
  • 调整窗口大小:Console.SetWindowSize(100, 40);(设置终端宽100字符、高40行)
  • 设置光标位置:Console.SetCursorPosition(0, 5);(将光标定位到第5行开头)

比如要标记重复的姓名,可以给重复项设置不同颜色:

Dictionary<string, int> nameCount = new Dictionary<string, int>();
foreach (string emp in employees)
{
    if (!nameCount.ContainsKey(emp))
        nameCount[emp] = 0;
    nameCount[emp]++;

    if (nameCount[emp] > 1)
        Console.ForegroundColor = ConsoleColor.Red;
    
    Console.WriteLine(emp);
    Console.ResetColor();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:10:29