用户kokos通过使用关键字回答了c#的隐藏特性问题。你能详细说明一下吗?使用的用途是什么?


当前回答

大括号之外的所有内容都将被处理,因此如果您不使用对象,则可以对它们进行处理。这是因为如果你有一个SqlDataAdapter对象,你在应用程序生命周期中只使用它一次,你只填充一个数据集,你不再需要它,你可以使用以下代码:

using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
   // do stuff
} // here adapter_object is disposed automatically

其他回答

大括号之外的所有内容都将被处理,因此如果您不使用对象,则可以对它们进行处理。这是因为如果你有一个SqlDataAdapter对象,你在应用程序生命周期中只使用它一次,你只填充一个数据集,你不再需要它,你可以使用以下代码:

using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
   // do stuff
} // here adapter_object is disposed automatically

它也可以用于创建作用域,例如:

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);
          }
      }
   }

}

using子句用于定义特定变量的作用域。

例如:

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 goes out of the defined scope.
}

using语句提供了一种方便的机制来正确使用IDisposable对象。作为规则,当您使用IDisposable对象时,您应该在using语句中声明并实例化它。

using语句以正确的方式调用对象上的Dispose方法,并且(如前面所示使用它时)它还会导致对象本身在调用Dispose时超出作用域。在using块中,对象是只读的,不能被修改或重新分配。

它来自这里。

可以通过以下示例使用别名命名空间:

using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;

正如你所看到的,这被称为使用别名指令,它可以用来隐藏冗长的引用,如果你想在你的代码中明显地引用什么 如。

LegacyEntities.Account

而不是

CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account

或者简单地

Account   // It is not obvious this is a legacy entity