【问题标题】:What the reason for enclosing code in a "using" in c# [duplicate]在c#中的“使用”中包含代码的原因是什么[重复]
【发布时间】:2013-02-25 17:01:27
【问题描述】:

我有以下代码:

        try
        {
            using (var context = new DataContext())
            {
                if (!context.Database.Exists())
                {
                    // Create the SimpleMembership database without Entity Framework migration schema
                    ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                }
            }


            WebSecurity.InitializeDatabaseConnection("xxx", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            var sql = System.IO.File.ReadAllText("SqlScript.sql");
            context.Database.ExecuteSqlCommand(sql);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
        }

有人能解释一下“使用”的目的是什么吗?

【问题讨论】:

  • 在外面使用你的变量正在被处理掉。这意味着您不需要显式关闭 FileStreams、数据库连接等。
  • manual有什么不明白的地方?

标签: c#


【解决方案1】:

"using" 语句的原因是为了确保对象始终是正确的disposed,并且不需要显式代码来确保发生这种情况。

using 语句简化了您必须编写的代码以创建并最终清理对象。

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

相当于:

MyResource myRes= new MyResource();
try
{
    myRes.DoSomething();
}
finally
{
    // Check for a null resource.
    if (myRes!= null)
        // Call the object's Dispose method.
        ((IDisposable)myRes).Dispose();
}

【讨论】:

    【解决方案2】:

    关键字using 用于实现IDisposable 接口的对象 - 它们包含非托管资源,如果对象被垃圾收集器收集,则这些资源不会被清除。
    使用using 时,您将对象的范围限制为花括号,而当留下using-Statement 时,所有非托管资源都将被处理掉。

    在此处查看this 文章。

    【讨论】:

      【解决方案3】:

      syntactic sugar 是正确的处理模式。

      相当于

      DataContext context = new DataContext();
      try
      {
         // using context here
      }
      finally
      {
        if(context != null)
          ((IDisposable)context).Dispose();
      }
      

      这在 using Statement 的 MSDN 文章中有所描述。

      以这种方式使用using 可确保正确处理并减少程序员出错的机会。

      【讨论】:

        【解决方案4】:

        using 在对象被使用后自动处理它。无需手动调用.Dispose()

        using (var context = new DataContext())
        {
            // other codes
        }  
        // at this point the context is already disposed
        

        相同
        var context = new DataContext()
        // other codes
        context.Dispose()    // manually calling Dispose()
        // at this point the context is already disposed
        

        【讨论】:

        • 完全一样。
        • 除了异常处理还是有区别的。所以这两个块并不是真的“相等”。请参阅 odeds 答案。
        【解决方案5】:

        using 语句确保 Dispose 在 using 块结束时被调用。您的代码相当于:

        var context = new DataContext();
        
        try
        { 
           if (!context.Database.Exists())
           {
               ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
           }
        }
        finally
        {
            if (context != null)
                context.Dispose();
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-10
          • 1970-01-01
          • 2016-07-30
          • 1970-01-01
          • 2013-09-13
          • 1970-01-01
          • 2014-12-24
          • 2011-07-28
          相关资源
          最近更新 更多