代码之家  ›  专栏  ›  技术社区  ›  Matt Croft

有没有办法将ConsoleColor值设置为等于变量?

  •  0
  • Matt Croft  · 技术社区  · 3 年前

    我正在创建一个类来支持我正在开发的控制台应用程序,我想在中创建一个方法来更改背景和前景色。有没有办法将ConsoleColor值(我认为这是一个枚举)设置为另一个变量,以便用户在运行时轻松更改?例如,我希望得到以下内容。

    Public class ConsoleOutput
    {
      private var consoleBackground = ConsoleColor.White;
      private var consoleForeground = ConsoleColor.Black;
      
      Public ConsoleOutput
      {
        Console.BackgroundColor = consoleBackground
        Console.ForegroundColor = consoleForeground
      }
    }
    

    然而,这并没有奏效。

    1 回复  |  直到 3 年前
        1
  •  1
  •   Mushroomator    3 年前

    你似乎从来没有在程序中写入控制台,这显然是你需要做的。除此之外,你还需要一种在运行时使用setters或类似函数来更改颜色的方法 ChangeColors()

    这里有一个工作示例程序供参考:

    namespace MyProgram;
    
    class Program
    {
        static void Main(string[] args)
        {
            var coloredPrinter = new ColoredPrinter(ConsoleColor.White, ConsoleColor.Blue);
            coloredPrinter.WriteLine("This is white text on blue background");
            coloredPrinter.ChangeColors(ConsoleColor.Yellow, ConsoleColor.Red);
            coloredPrinter.WriteLine("This is yellow text on red background");
            Console.WriteLine("This is the default");
        }
    }
    
    class ColoredPrinter
    {
        public ConsoleColor ForegroundColor { get; set; }
        public ConsoleColor BackgroundColor { get; set; }
    
        public ColoredPrinter(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
        {
            ChangeColors(foregroundColor, backgroundColor);
        }
    
        public void ChangeColors(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
        {
            ForegroundColor = foregroundColor;
            BackgroundColor = backgroundColor;
        }
    
        public void WriteLine(string text)
        {
            Console.ResetColor();
            Console.BackgroundColor = BackgroundColor;
            Console.ForegroundColor = ForegroundColor;
            Console.WriteLine(text);
            Console.ResetColor();
        }
    }
    
    

    这会打印出以下内容:

    colored console output

    推荐文章