10个C#程序员经常用到的实用代码片段

2019-12-26 13:40:17丽君

借助于using语法,像下面的代码所示,可以检查一段代码的运行时间,并打印在控制台上。

 

 
  1. using (new AutoStopwatch())   {  
  2. Decimal total2 = 0;   int limit2 = 1000000;  
  3. for (int i = 0; i < limit2; ++i)   {  
  4. total2 = total2 + (Decimal)Math.Sqrt(i);   }  
  5. }  

10 使用光标

当程序正在后台运行保存或是册除操作时,应当将光标状态修改为忙碌。可使用下面的技巧。

 

  1. class AutoWaitCursor : IDisposable   {  
  2. private Control _target;   private Cursor _prevCursor = Cursors.Default;  
  3. public AutoWaitCursor(Control control)   {  
  4. if (control == null)   {  
  5. throw new ArgumentNullException(“control”);   }  
  6. _target = control;   _prevCursor = _target.Cursor;  
  7. _target.Cursor = Cursors.WaitCursor;   }  
  8. public void Dispose()   {  
  9. _target.Cursor = _prevCursor;   }  
  10. }