What are the uses of “using” in C#?

后端 未结 29 2902
有刺的猬
有刺的猬 2020-11-21 07:31

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of

29条回答
  •  天涯浪人
    2020-11-21 07:40

    It also can be used for creating scopes for Example:

    class LoggerScope:IDisposable {
       static ThreadLocal threadScope = 
            new ThreadLocal();
       private LoggerScope previous;
    
       public static LoggerScope Current=> threadScope.Value;
    
       public bool WithTime{get;}
    
       public LoggerScope(bool withTime){
           previous = threadScope.Value;
           threadScope.Value = this;
           WithTime=withTime;
       }
    
       public void Dispose(){
           threadScope.Value = previous;
       }
    }
    
    
    class Program {
       public static void Main(params string[] args){
           new Program().Run();
       }
    
       public void Run(){
          log("something happend!");
          using(new LoggerScope(false)){
              log("the quick brown fox jumps over the lazy dog!");
              using(new LoggerScope(true)){
                  log("nested scope!");
              }
          }
       }
    
       void log(string message){
          if(LoggerScope.Current!=null){
              Console.WriteLine(message);
              if(LoggerScope.Current.WithTime){
                 Console.WriteLine(DateTime.Now);
              }
          }
       }
    
    }
    

提交回复
热议问题