What are the uses of “using” in C#

2018-12-31 02:42发布

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 using?

29条回答
妖精总统
2楼-- · 2018-12-31 03:02

Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.

This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.

查看更多
只靠听说
3楼-- · 2018-12-31 03:03

It also can be used for creating scopes for Example:

class LoggerScope:IDisposable {
   static ThreadLocal<LoggerScope> threadScope = 
        new ThreadLocal<LoggerScope>();
   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);
          }
      }
   }

}
查看更多
与风俱净
4楼-- · 2018-12-31 03:04

When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.

查看更多
浮光初槿花落
5楼-- · 2018-12-31 03:05

The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

This comes from: here

查看更多
栀子花@的思念
6楼-- · 2018-12-31 03:06

Not that it is ultra important, but using can also be used to change resources on the fly. Yes disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.

查看更多
荒废的爱情
7楼-- · 2018-12-31 03:06

Using Clause is used to define the scope for the particular variable. For example:

     Using(SqlConnection conn=new SqlConnection(ConnectionString)
            {
                Conn.Open()
            // Execute sql statements here.
           // You do not have to close the connection explicitly here as "USING" will close the connection once the object Conn becomes out of the defined scope.
            }
查看更多
登录 后发表回答