在 Console.WriteLine 中调用 void 方法

发布于 2025-01-09 10:27:24 字数 1338 浏览 2 评论 0原文

我正在开发一个 C# 控制台项目,但我对 C# 还完全陌生。我的问题是:我可以在 Console.WriteLine(); 中调用 void 方法吗?也许类似于

static void ChangeColor()
{
   Console.backgroundColor = ConsoleColor.Red
};

Console.WriteLine("Hello *Calling method *ChangeColor();* * my friend!"); 

我的代码中的示例:

                Console.Write(
$@"
____________________________________________________________________________________________________
|                                                                                                  |
|                         __     __                                                                |
|                        / / \__/\ \                                                               |
|                        \/| /\/\|\/                                                               |");
                DarkBlueTxt();
                Console.Write(
$@"
|                        __||o o||__                                                               |
|                       / . \__/ .  \                                                              |
|                      /.  .(__).  . \                                                             |
|______________________\ .  /__\ .   /_____________________________________________________________|");

I am working on a C# console project, but I am yet totally new in C#. My question is: can I call a void method in Console.WriteLine();? Maybe something like

static void ChangeColor()
{
   Console.backgroundColor = ConsoleColor.Red
};

Console.WriteLine("Hello *Calling method *ChangeColor();* * my friend!"); 

An example from my code:

                Console.Write(
$@"
____________________________________________________________________________________________________
|                                                                                                  |
|                         __     __                                                                |
|                        / / \__/\ \                                                               |
|                        \/| /\/\|\/                                                               |");
                DarkBlueTxt();
                Console.Write(
$@"
|                        __||o o||__                                                               |
|                       / . \__/ .  \                                                              |
|                      /.  .(__).  . \                                                             |
|______________________\ .  /__\ .   /_____________________________________________________________|");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

假装爱人 2025-01-16 10:27:25

Caius Jard 提出的解决方案的变体:

void WriteWithColors(params (ConsoleColor? Color, string Text)[] colorizedTextCollection)
{
    foreach (var colorizedText in colorizedTextCollection)
    {
        Console.BackgroundColor = colorizedText.Color ?? Console.BackgroundColor;
        Console.Write(colorizedText.Text);
    }
}
  • 这里您可以不接收 objectt 数组,而是可以传递颜色和文本元组
  • 通过这种方法,foreach 的主体变得更简单

示例用法:

WriteWithColors((ConsoleColor.Red, "red"), 
                (null, "still red"), 
                (ConsoleColor.DarkBlue, "blue"));

A variant of Caius Jard's proposed solution:

void WriteWithColors(params (ConsoleColor? Color, string Text)[] colorizedTextCollection)
{
    foreach (var colorizedText in colorizedTextCollection)
    {
        Console.BackgroundColor = colorizedText.Color ?? Console.BackgroundColor;
        Console.Write(colorizedText.Text);
    }
}
  • Instead of receiving an object array, here you can pass color and text tuples
  • With this approach the foreach's body become a bit simpler

Sample usage:

WriteWithColors((ConsoleColor.Red, "red"), 
                (null, "still red"), 
                (ConsoleColor.DarkBlue, "blue"));
反差帅 2025-01-16 10:27:25

谢谢大家!你们都有很好的答案。为了保持简单,现在我将绘图的每个不同颜色部分放置在不同的方法中,然后一一调用零件和颜色方法,这是我认为最简单的方法,即使我不想这样做就像这样,但不幸的是我想要的似乎不存在。再次感谢您的回答!

Thanks to everybody! You all have really good answers. To keep it simple for now I have placed each different colored part of the drawing in a different method and then called the parts and color methods one by one, that was the easiest way I think, even when I didn't want to do it like that but unfortunately what I wanted seems not to be existing. Thanks again for your answers!

赠意 2025-01-16 10:27:24

也许让自己成为一个辅助方法:

void WriteWithColors(params object[] p){

  foreach(var o in p){
    if(o is ConsoleColor)
      Console.BackgroundColor = (ConsoleColor)o;
    else
      Console.Write(o);
  }
}

然后像这样调用它:

WriteWithColors(ConsoleColor.Red, @"
____________________________________________________________________________________________________
|                                                                                                  |
|                         __     __                                                                |
|                        / / \__/\ \                                                               |
|                        \/| /\/\|\/                                                               |", ConsoleColor.Blue, @"
|                        __||o o||__                                                               |
|                       / . \__/ .  \                                                              |
|                      /.  .(__).  . \                                                             |
|______________________\ .  /__\ .   /_____________________________________________________________|");

编译器会将颜色和字符串的混合捆绑到一个对象数组中,然后方法中的循环遍历它,要么更改颜色,要么根据它的内容打印字符串是(颜色或字符串)

如果您不在字符串中使用 {placeholders} ,则不需要在字符串的头部添加 $ 顺便说一句

Perhaps make yourself a helper method:

void WriteWithColors(params object[] p){

  foreach(var o in p){
    if(o is ConsoleColor)
      Console.BackgroundColor = (ConsoleColor)o;
    else
      Console.Write(o);
  }
}

And then call it like:

WriteWithColors(ConsoleColor.Red, @"
____________________________________________________________________________________________________
|                                                                                                  |
|                         __     __                                                                |
|                        / / \__/\ \                                                               |
|                        \/| /\/\|\/                                                               |", ConsoleColor.Blue, @"
|                        __||o o||__                                                               |
|                       / . \__/ .  \                                                              |
|                      /.  .(__).  . \                                                             |
|______________________\ .  /__\ .   /_____________________________________________________________|");

The compiler will bundle your mix of Colors and strings up into an object array and then the loop in the method goes through it either changing the color or printing the string depending on what it is (a color or a string)

You don't need $ on the head of a string if you don't use {placeholders} within the string btw

高冷爸爸 2025-01-16 10:27:24

只是为了好玩,您可以严重滥用新的 C# 10 内插字符串处理程序让您编写例如:

WriteColoredText($"First{ConsoleColor.Red}Second");

请不要在实践中实际这样做 - 这是一个可怕的黑客,没有人会理解。使用 @CauisJard 的答案:它可能更清晰,也更简单。但这是对新插值字符串处理程序功能的有趣探索。

话虽如此,就这样吧。

首先,我们需要定义自己的插值字符串处理程序,我们将包装 StringBuilder.AppendInterpolatedStringHandler,因为它主要完成我们想要的事情。但是,当写入 ConsoleColor 时,我们将记录下来,最终得到一个段列表,其中每个段都是一段文本以及要写入的颜色:

[InterpolatedStringHandler]
public struct ConsoleColorInterpolatedStringHander
{
    private readonly StringBuilder sb = new();
    private StringBuilder.AppendInterpolatedStringHandler appendHandler;
    private ConsoleColor? currentColor = null;
    public List<(ConsoleColor?, string)> Segments { get; } = new();
    
    public ConsoleColorInterpolatedStringHander(int literalLength, int formattedCount)
    {
        appendHandler = new(literalLength, formattedCount, sb);
    }

    public void AppendLiteral(string value) => appendHandler.AppendLiteral(value);
    public void AppendFormatted<T>(T value) => appendHandler.AppendFormatted(value);
    public void AppendFormatted<T>(T value, string? format) => appendHandler.AppendFormatted(value, format);
    public void AppendFormatted<T>(T value, int alignment) => appendHandler.AppendFormatted(value, alignment);
    public void AppendFormatted<T>(T value, int alignment, string? format) => appendHandler.AppendFormatted(value, alignment, format);
    
    public void AppendFormatted(ConsoleColor color)
    {
        Segments.Add((currentColor, sb.ToString()));
        sb.Clear();
        currentColor = color;
    }
    
    public void Finish()
    {
         Segments.Add((currentColor, sb.ToString()));   
    }
}

然后我们需要定义接受此处理程序的方法:

public static void WriteColoredText(ConsoleColorInterpolatedStringHanderhandler)
{
    handler.Finish();
    foreach (var (color, text) in handler.Segments)
    {
        if (color != null)
        {
            Console.BackgroundColor = color.Value;
        }
        Console.Write(text);
    }
}

然后我们可以将内插字符串传递给新的 WriteColoredText 方法。任何包含 ConsoleColor 的占位符都会导致背景颜色发生变化。

<一href="https://sharplab.io/#v2:EYLgtghglgdgNAFxAJwK7wCYgNQB8ACATAIwCwAUPgAwAE+xAdAEro JRgCmDAwgPZgAHKABsOyAMpiAblADGHAM4BuCtTqMAKhwAeCFZVr0ALPOoBiGKmHCIwUTQ4xboihQDaASRgI xA3jZ8McQRkWABzAAkIGAxRZABdVQBmGgUQ1FkEGj4YBX8OPmFeZC8fZD8AjiCQ8KiYsQoAbwoaVpoBUKkIH xpkDggMXhhhAE8aYNCYMIAhVBEMMVTgGgBeGhgOAHcACgBKfTb2zu6OcZqp2fmxBgBBAQFHDFLffxPqycjo2 MWIe8e677IA5tDpQLo9HJ5USFYoAfhoslQyD63hhyFW6yswmBrXwKQAMlA0gAebaQ/Jo2FwdRUXYAPnGHDCn G8ChojRoYQ4ehoAF8MRsdvsWm0RbiUuTof5is9yq9AhNal8xNTYFlhFAyhBhPjHGEEAALalqmgAM2KkAQgT4 rF2YvZ9sOvweMQBcQFW22Gq1Or1hup5uQlutvFY1IUwGF5EOvNc0baeLoRhodxdGEJPu29FoXWEqA4u1WDOD /y+cVufxiGbE2u2ufzUcOifwydTjwAYhbuoFiRo6dsNDR6wWizQS66y9c2zFO0Hu1U69qGzi6CkWynKxhZ8Gq r3+4Ph9Ts/DA5bCyti5u3VPN9v5xhF3mOAGuwhGwm163b6+e32B0Ol2fGgTW1KAwhgFk31HccMGvZAKzTO8r QXQ8xw1cDIPfcUkw3RCf13P8D0A41vDQsCIMCBAj2IKgT1fc9LzTOCEI7fCH1Q0CMMo85zfFd7WbL88N4wI ySGKECmldFZCku141aZp5MORlmUohRbgwB9tkRZFKLRcNGAYDReEVKY9l2LDlIjHhRAgZA9hXQ4dJRBA0QxG SiiBe1YyUgTPxodtYCJA09ntRTlMOSRVNZDStOcvSpiMoyTPOMJzP2UUlJ8nzkjoQhsiaATCEIMLHTaAB1UIf DRKotF0bYABIACIIg4axeEaSVJM85gql5crimEDAmssnzDj89QADYcMqzVuuKWqdAQMTcgpKTZQqN5TM+ep0 QNSdkDkw5woimh9pictApgYKHLK1pA36WQDRoRd0W0xKaB8XRC1gM6DoYKLIIUI7TpO062igU0Xo84oaAAQj WSxrBB8GFLu1GuoYAYIFkaBrMJkFDGI3LWGH4IANUAxzUdaAB6WnxlgeRxn2gR8VsGhBkUGAAHIsgUA1eE2B EpIUalNg4HnrCOE1DSJMc2Ql6x0fBzHZp8RqmuJRoyYYSmn15OkRupiKxpp7JxPyBh1Y4bYvr49GzdabKgA = rel="nofollow noreferrer">在 SharpLab 上查看。

要了解发生了什么,请切换到 SharpLab 上的 C# 视图。重要的是编译器已将对 WriteColoredText 的调用写入:

public static void Main()
{
    ConsoleColorInterpolatedStringHander handler = new ConsoleColorInterpolatedStringHander(10, 1);
    handler.AppendLiteral("Hello");
    handler.AppendFormatted(ConsoleColor.Red);
    handler.AppendLiteral("World");
    WriteColoredText(handler);
}

Just for fun, you can heavily abuse the new C# 10 Interpolated string handlers to let you write e.g.:

WriteColoredText(
quot;First{ConsoleColor.Red}Second");

Please don't actually do this in practice -- it's a horrible hack which noone will understand. Use @CauisJard's answer instead: it's probably clearer, and much simpler. But this is a fun exploration of the power of the new interpolated string handlers.

With that said, here goes.

First, we'll need to define our own interpolated string handler, We'll wrap StringBuilder.AppendInterpolatedStringHandler, as that mainly does what we want. However, when a ConsoleColor is written, we'll record this, ending up with a list of segments, where each segment is a section of text and the color to write it in:

[InterpolatedStringHandler]
public struct ConsoleColorInterpolatedStringHander
{
    private readonly StringBuilder sb = new();
    private StringBuilder.AppendInterpolatedStringHandler appendHandler;
    private ConsoleColor? currentColor = null;
    public List<(ConsoleColor?, string)> Segments { get; } = new();
    
    public ConsoleColorInterpolatedStringHander(int literalLength, int formattedCount)
    {
        appendHandler = new(literalLength, formattedCount, sb);
    }

    public void AppendLiteral(string value) => appendHandler.AppendLiteral(value);
    public void AppendFormatted<T>(T value) => appendHandler.AppendFormatted(value);
    public void AppendFormatted<T>(T value, string? format) => appendHandler.AppendFormatted(value, format);
    public void AppendFormatted<T>(T value, int alignment) => appendHandler.AppendFormatted(value, alignment);
    public void AppendFormatted<T>(T value, int alignment, string? format) => appendHandler.AppendFormatted(value, alignment, format);
    
    public void AppendFormatted(ConsoleColor color)
    {
        Segments.Add((currentColor, sb.ToString()));
        sb.Clear();
        currentColor = color;
    }
    
    public void Finish()
    {
         Segments.Add((currentColor, sb.ToString()));   
    }
}

We then need to define a method which accepts this handler:

public static void WriteColoredText(ConsoleColorInterpolatedStringHanderhandler)
{
    handler.Finish();
    foreach (var (color, text) in handler.Segments)
    {
        if (color != null)
        {
            Console.BackgroundColor = color.Value;
        }
        Console.Write(text);
    }
}

We can then pass an interpolated string to our new WriteColoredText method. Any placeholders which contain a ConsoleColor cause the background color to change.

See it on SharpLab.

To get an idea of what's going on, switch to the C# view on SharpLab. The important bit is that the compiler has written our call to WriteColoredText into:

public static void Main()
{
    ConsoleColorInterpolatedStringHander handler = new ConsoleColorInterpolatedStringHander(10, 1);
    handler.AppendLiteral("Hello");
    handler.AppendFormatted(ConsoleColor.Red);
    handler.AppendLiteral("World");
    WriteColoredText(handler);
}
梦里梦着梦中梦 2025-01-16 10:27:24

您可以检查 ANSI 颜色,但它需要特定的控制台模式,链接中对此进行了说明。

static void Main(string[] args)
{
    Console.WriteLine("\u001b[31mHello World!\u001b[0m");
}

来源:
在 .NET Core 控制台中使用 ANSI 颜色代码应用程序

You could check ANSI colors, but it requires a certain console mode which is explained in the link.

static void Main(string[] args)
{
    Console.WriteLine("\u001b[31mHello World!\u001b[0m");
}

Source:
Using ANSI colour codes in .NET Core Console applications

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文