为Console添加扩展方法

Console中都是静态方法,有的时候我们可以需要一些特别的颜色和状态显示,
需要不停的重置Console的字体,一行行写代码有的时候我会觉得麻烦。
这里提供一种思路,学习Linq里面的链式调用,我们可以做到更多。

 1 namespace System
 2 {
 3     public static class ConsoleX
 4     {
 5         private static readonly IConsoleExecutable executor;
 6 
 7         static ConsoleX()
 8         {
 9             executor = new ConsoleExecutor();
10         }
11 
12         public static IConsoleExecutable WriteLineColor(ConsoleColor color, string message, params object[] para)
13         {
14             return executor.WriteLineColor(color, message, para);
15         }
16 
17         public static IConsoleExecutable WriteColor(ConsoleColor color, string message, params object[] para)
18         {
19             return executor.WriteColor(color, message, para);
20         }
21 
22         public static IConsoleExecutable Error(Exception e)
23         {
24             return executor.Error(e);
25         }
26 
27         private class ConsoleExecutor : IConsoleExecutable
28         {
29             #region IConsoleExecutable Members
30 
31             public IConsoleExecutable WriteLineColor(ConsoleColor color, string message, params object[] para)
32             {
33                 Console.ForegroundColor = color;
34                 Console.WriteLine(message, para);
35                 Console.ResetColor();
36                 return this;
37             }
38 
39             public IConsoleExecutable WriteColor(ConsoleColor color, string message, params object[] para)
40             {
41                 Console.ForegroundColor = color;
42                 Console.Write(message, para);
43                 Console.ResetColor();
44                 return this;
45             }
46 
47             public IConsoleExecutable Error(Exception e)
48             {
49                 WriteLineColor(ConsoleColor.Red, e.ToString());
50                 return this;
51             }
52 
53             #endregion
54         }
55     }
56 
57     public interface IConsoleExecutable
58     {
59         IConsoleExecutable WriteLineColor(ConsoleColor color, string message, params object[] para);
60 
61         IConsoleExecutable WriteColor(ConsoleColor color, string message, params object[] para);
62 
63         IConsoleExecutable Error(Exception e);
64     }
65 }
View Code

 

 

转载于:https://www.cnblogs.com/seraphim/p/4361755.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值