c# - 临时更改一个值(文本颜色)并在一些操作后恢复它(打印文本)
问题描述
我想创建一个“变量”,将文本颜色更改为绿色,无论您在其花括号中打印什么,但是当花括号关闭时,它会将控制台文本颜色更改为灰色,以便我打印下一个内容。
所以简而言之,我想做的是:
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("test");
Console.ForegroundColor = ConsoleColor.gray;
但是由于我的代码中有很多内容,所以我想像这样缩短它:
mycmd(green, gray)
{
Console.WriteLine("test");
}
解决方案
你可以做这样的事情
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");
});
推荐阅读
- php - 使用 PHP 计算 PDF 中的页数
- r - 在闪亮的 R 中的下载处理程序中使用 promise 对象
- python - argparse 多个可选参数
- php - 使用ajax在Php中以“电子邮件已存在”条件提交表单
- mysql - 将'b'文字放在非位值之前时如何处理MySQL WorkBench位(1)错误?
- javascript - request.js 回调不遵循脚本顺序
- reactjs - Preact 路由器:同一个组件的多个路径名
- c# - 需要提取二维数组 (256x256) 中的所有单元格,这些单元格落在以原点为中心的扇区中,并将所有其他单元格标记为零
- angular - 在带有父子路由的反应式表单中使用 patchValue
- dbus - dbus-1.0/dbus/dbus.h:29:10:致命错误:找不到“dbus/dbus-arch-deps.h”文件