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

如何修改C#控制台应用中Console.WriteLine的前景色?

如何在控制台输出中为标题设置不同颜色

嘿,作为控制台开发新手,你碰到的这个颜色控制问题其实很常见——核心点在于控制台的颜色是全局状态,没法通过一次性输出拼接好的字符串来实现局部颜色变化,得拆分输出步骤,在输出不同颜色内容前切换颜色。

你的原代码用StringBuilder把所有内容攒在一起一次性输出,这样所有文本都会用当前的默认颜色显示。要实现你要的「青色标题 + 白色内容」效果,我们需要分步骤输出:

核心思路

  1. 输出标题前,设置控制台前景色为ConsoleColor.Cyan
  2. 输出标题文本(比如TITLE:)
  3. 把前景色改回ConsoleColor.White
  4. 输出对应的具体信息
  5. 所有内容输出完毕后,建议调用Console.ResetColor()恢复默认控制台颜色,避免影响后续操作

修改后的完整代码

// 输出标题行
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("TITLE: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"{title} - EP {episode}/{totalEpisode}");

// 输出时长
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("DURATION: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(_duration);

// 输出分类
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("CATEGORY: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(category);

// 输出状态
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("STATUS: ");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"{releaseStatus} ({totalEpisode} EP)");

// 输出720p链接区块
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("720p Direct Link:");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" DIRECT LINK: {directLink720p}");
Console.WriteLine($" BITRATE: {bitrate}");
Console.WriteLine($" RESOLUTION: {width}x{height}p");
Console.WriteLine($" DURATION: {duration}");
Console.WriteLine($" FILESIZE: {filesize}");
Console.WriteLine($" CODEC: {codec}");

// 输出字幕区块
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("SUBTITLE:");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" SUBTITLE URL: {subURL}");
Console.WriteLine($" SUBTITLE LANG: {subName}");

// 输出视频和音频信息
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("VIDEO:");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" {_array[0]}");

Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("AUDIO:");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($" {_array[1]}");

// 恢复默认控制台颜色
Console.ResetColor();

额外小技巧

如果觉得反复写Console.ForegroundColor太繁琐,可以封装一个小方法来简化操作:

static void ColoredWrite(string text, ConsoleColor color)
{
    var originalColor = Console.ForegroundColor;
    Console.ForegroundColor = color;
    Console.Write(text);
    Console.ForegroundColor = originalColor;
}

这样用的时候就可以写成:

ColoredWrite("TITLE: ", ConsoleColor.Cyan);
Console.WriteLine($"{title} - EP {episode}/{totalEpisode}");

能少写不少重复代码哦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:42:28