如何在使用 return 时更改方法中的颜色

How do I change the Color in a Method while using return

我想先更改颜色

$"Abteilung        { _name}

喜欢红色然后改回其他颜色

那部分是我的代码。

public string AsString()
        {
  return
            $"{Console.ForegroundColor = ConsoleColor.Red}" +
            $"Abteilung        { _name}\n" +
            $"{Console.ForegroundColor = ConsoleColor.Blue}" +
            $"Flaeche          {_flaeche} m2\n" +
            $"Abteilungsleiter {_abteilungsleiter.Vorname} {_abteilungsleiter.Nachname}\n" +
            $"Angestellte      {angestellte}\n" +
            $"Artikel          {ausgabeArtikel}\n";
        }

它改变了颜色,但对于所有文本,它是这样做的: 我不想像 RedAbteilung 和 BlueFlaeche

$"{Console.ForegroundColor = ConsoleColor.Red}"

虽然在插值中断内执行控制台颜色分配可能是合法的,但这可能不是您想要的,因为分配 returns 分配的值随后将被捕获到字符串中,并且打印。您需要将报表拆分:

Console.ForegroundColor = ConsoleColor.Red;
Console.Write("this is red");
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write(" and this is blue");

如果您正在为此寻找一些活力,也许就像 Rufus 评论的那样:

var msgs = new List<(ConsoleColor C, string S)>();
msgs.Add((ConsoleColor.Red, "it’s red"));
msgs.Add((ConsoleColor.Blue, "it’s blue"));

然后

foreach(var msg in msgs){
    Console.ForegroundColor = msg.C;
    Console.Write(msg.S);
}

我还在评论中链接了一些重复的东西,如果你正在寻找一种打印方式,例如Console.Write("\x1b[48;5;1mit's red!\x1b[48;5;4mit's blue!") - 首先有一些 p/invoke 工作要做。也许一些已经这样做的图书馆会适合你..

除非您愿意 a) 在返回值本身中包含某种标记,并且 b) 在显示字符串时编写额外的代码来解释该标记,否则您无法使用 ToString() 覆盖来实现此目的。

例如,像这样:

class Program
{
    static void Main(string[] args)
    {
        A a = new A { Name = "name1", Text = "this is the object text" };

        WriteLineWithColor(a.ToString());
    }

    static void WriteLineWithColor(string textWithMarkup)
    {
        ConsoleColor previousColor = Console.ForegroundColor;
        int lastIndex = 0;

        try
        {
            foreach (Match match in Regex.Matches(textWithMarkup, @"\[(?<color>.+?)\]"))
            {
                Console.Write(textWithMarkup.Substring(lastIndex, match.Index - lastIndex));

                if (Enum.TryParse<ConsoleColor>(match.Groups["color"].Value, out ConsoleColor color))
                {
                    Console.ForegroundColor = color;
                }
                else
                {
                    Console.Write(match.Value);
                }

                lastIndex = match.Index + match.Length;
            }

            Console.WriteLine(textWithMarkup.Substring(lastIndex));
        }
        finally
        {
            Console.ForegroundColor = previousColor;
        }
    }
}

class A
{
    public string Name { get; init; }
    public string Text { get; init; }

    public override string ToString()
    {
        return $"[Red]{Name} [Blue]{Text}";
    }
}

Outlook 看起来像这样:

从 Windows10 开始,命令提示符控制台现在支持 VT100“智能终端”颜色代码,这是上述主题的变体。参见例如this answer to Custom text color in C# console application?。您仍然需要在返回的字符串中包含标记(这使得它在其他上下文中显示的用处不大,例如在调试器中)但它与上面的方法相同并且不需要额外的代码来实际处理字符串.