C# 中的 Console.ForegroundColor 属性17 Mar 2025 | 4 分钟阅读 在本文中,我们将讨论 C# 中的 Console.ForegroundColor 属性及其语法、参数和示例。 什么是 Console.ForegroundColor 属性?Console.ForegroundColor 是 C# 中的一个属性。它是 Console 类的一部分,指定 Console 的前景颜色。此属性的默认颜色是灰色。此属性也用于更改 Console 中输出文本的颜色。它使 Console 看起来不同,并提高了控制台应用程序的可读性。它帮助用户快速识别每条消息的严重性。 此属性将增强可读性并提供有关信息性质的视觉提示。在某些应用程序中,红色用于指示错误,绿色用于指示成功等。此属性在创建基于控制台的用户界面时很有用。 语法C# 中 Console.ForegroundColor 的语法 此属性不需要任何参数,其返回类型为 void。为此属性赋予一个颜色值,以便可以更改输出上下文文本。语法中的 colorName 可以是任何颜色,其中一些是红色、蓝色、黄色等。 示例让我们看一个简单的程序来演示 C# 中的 Console.ForegroundColor 属性。 输出 ![]() 说明 此程序解释了 C# 中颜色更改属性的用法。最初,控制台的文本是白色。因此,可以通过使用ForegroundColor来更改它。这里,颜色设置为红色。之后,它变为黄色,然后变为绿色。最后,通过使用控制台类中存在的ResetColor属性,将控制台设置回其默认颜色。 示例 2让我们看一个简单的程序来演示 C# 中的 Console.ForegroundColor。 输出 Enter user names and select a color (or 'done' to finish): Enter user name (or 'done' to finish): ramu Available colors: 1. Red 2. Green 3. Blue 4. Yellow 5. Cyan Enter the number of the color: 2 Enter user name (or 'done' to finish): sita Available colors: 1. Red 2. Green 3. Blue 4. Yellow 5. Cyan Enter the number of the color: red Enter user name (or 'done' to finish): done Welcome to the Console Chat! Enter 'q' to quit. Select user name (or 'q' to quit): ramu Enter your message: Hi Sita, have you heard about the latest advancements in Artificial Intelligence (AI) and Machine Learning (ML)? It's fascinating how these technologies are transforming various industries! ramu: Hi Sita, have you heard about the latest advancements in Artificial Intelligence (AI) and Machine Learning (ML)? It's fascinating how these technologies are transforming various industries! Select user name (or 'q' to quit): sita Enter your message: Hi Ramu! Yes, I've been reading about AI and ML lately. It's incredible how they're revolutionizing everything from healthcare to finance. I'm particularly interested in their applications in predictive analytics and natural language processing. sita: Hi Ramu! Yes, I've been reading about AI and ML lately. It's incredible how they're revolutionizing everything from healthcare to finance. I'm particularly interested in their applications in predictive analytics and natural language processing. Select user name (or 'q' to quit): q Goodbye! 说明 此程序演示了 ForegroundColor 属性的用法。首先,在程序中导入必要的命名空间。之后,初始化一个键为字符串、值为颜色的字典。接下来,使用 while 循环 从用户那里获取输入。在这里,用户将提供一些名称及其对应的颜色。 之后,将键值对添加到字典中。如果用户输入“done”,while 循环将中断。现在,应用程序将启动,用户将输入用户的姓名和消息。此消息将使用该颜色打印到控制台。此 while 循环将在输入 “q” 时停止。最后,打印“再见”消息,表示应用程序已结束。 下一个主题C# 中多维数组和交错数组的区别 |
我们请求您订阅我们的新闻通讯以获取最新更新。