首页 > 解决方案 > 临时更改一个值(文本颜色)并在一些操作后恢复它(打印文本)

问题描述

我想创建一个“变量”,将文本颜色更改为绿色,无论您在其花括号中打印什么,但是当花括号关闭时,它会将控制台文本颜色更改为灰色,以便我打印下一个内容。

所以简而言之,我想做的是:

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("test");
Console.ForegroundColor = ConsoleColor.gray;

但是由于我的代码中有很多内容,所以我想像这样缩短它:

mycmd(green, gray)
{
    Console.WriteLine("test");
}

标签: c#

解决方案


你可以做这样的事情

public static void ColorAndWrite(ConsoleColor c1, ConsoleColor c2, string text)
{
   Console.ForegroundColor = c1;
   Console.WriteLine(text);
   Console.ForegroundColor = c2;
}

用法

ColorAndWrite(ConsoleColor.Black,ConsoleColor.Blue, "asdads");

或使用Action

public static void ColorFancy(ConsoleColor c1, ConsoleColor c2, Action action)
{
   Console.ForegroundColor = c1;
   action.Invoke();
   Console.ForegroundColor = c2;
}

用法

ColorFancy(ConsoleColor.Black, ConsoleColor.Blue, () =>  Console.WriteLine("dfgdfgdfgdfg"));

// or

ColorFancy(ConsoleColor.Black, ConsoleColor.Blue, () =>
      {
         // lots of things here
         Console.WriteLine("dfgdfgdfgdfg");
      });

推荐阅读