Console output is a commonly used debugging and information display method in programs. The Console class in the C# language provides a series of methods to control the style and color of console output. Among them, the Console.ForegroundColor function is used to set the foreground color of the console output (that is, the color of the text).
To use the Console.ForegroundColor function, we first need to introduce the System namespace. The code example is as follows:
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { // 设置控制台输出的前景色为红色 Console.ForegroundColor = ConsoleColor.Red; // 进行输出 Console.WriteLine("这是一段红色的文本"); // 设置控制台输出的前景色回归默认值 Console.ResetColor(); // 进行输出 Console.WriteLine("这是默认的文本颜色"); // 保持控制台窗口打开状态 Console.ReadLine(); } } }
In the above code, we first pass Console.ForegroundColor = ConsoleColor.Red
Set the foreground color of the console output to red. Afterwards, when outputting through Console.WriteLine
, you can see that the output text color is set to red. Immediately afterwards, return the foreground color of the console output to the default value through Console.ResetColor()
. The subsequent output text color will be the default color.
Through the above code example, we can easily use C#'s Console.ForegroundColor function to set the foreground color of the console output. This is very useful in scenarios such as display of debugging information and output formatting. By flexibly setting different foreground colors, we can make the console output more readable and colorful, and improve the effect of program debugging and display.
The above is the detailed content of Set the foreground color of console output using the Console.ForegroundColor function in C#. For more information, please follow other related articles on the PHP Chinese website!