0

次のコードがあります。

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

誰かが「使用」の目的を説明できますか?

4

5 に答える 5

3

これは、適切な破棄パターンのシンタックス シュガーです。

と同等です

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

これについては、MSDN の記事で説明されていusing Statementます。

このように使用usingすると、適切な破棄が保証され、プログラマーのミスの可能性が減少します。

于 2013-03-10T13:58:04.420 に答える
1

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
于 2013-03-10T13:58:02.330 に答える
0

usingDisposeステートメントは、using ブロックの最後に呼び出されることを保証します。あなたのコードは以下と同等です:

var context = new DataContext();

try
{ 
   if (!context.Database.Exists())
   {
       ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
   }
}
finally
{
    if (context != null)
        context.Dispose();
}
于 2013-03-10T13:57:51.690 に答える
0

このステートメントの理由は"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();
}
于 2013-03-10T13:59:18.767 に答える
0

キーワードusingは、インターフェイスを実装するオブジェクトに使用されますIDisposable。オブジェクトがガベージ コレクターによって収集された場合、それらはクリアされないアンマネージ リソースを含んでいます。
使用usingする場合は、オブジェクトのスコープを中かっこに制限し、using-Statement を残すと、すべての管理されていないリソースが破棄されます。

こちらの記事をご覧ください

于 2013-03-10T13:59:47.260 に答える