簡體   English   中英

我正確使用“使用”聲明嗎?

[英]Am I using the “using” statement correctly?

我想知道我的using是否正確。 using狀態中,我決定是否應該在游戲中使用圖像。

Image imageOfEnemy;
using(imageOfEnemy=Bitmap.FromFile(path))
{
   // some stuff with the imageOfEnemy variable

}

根據我的理解,我現在不需要調用Dispose

是的,您正確使用它。 您不需要顯式處理Bitmap,因為它將由using語句處理。 您可以通過在內部聲明圖像變量來進一步簡化:

using(var imageOfEnemy = Bitmap.FromFile(path))
{
    // some stuff with the imageOfEnemy variable
}

這大致相當於:

{
    var imageOfEnemy = Bitmap.FromFile(path);
    try 
    {
        // some stuff with the imageOfEnemy variable
    }
    finally 
    {
        ((IDisposable)imageOfEnemy).Dispose();
    }
}

它是正確的,如果Image實現了IDisposable接口。 using語句允許程序員指定何時使用資源的對象應該釋放它們。 提供給using語句的對象必須實現IDisposable接口。 此接口提供Dispose方法,該方法應釋放對象的資源。

using是IDisposable對象的簡寫語句,用於簡化try-finally塊,在finally塊中使用Dispose。

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

所以,是的,在這種情況下你不必“手動”調用Dispose。

using System;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var example = new Example())
            {
                //do something
            }
        }
    }

    class Example : IDisposable
    {

        public void Dispose()
        {
            //Do something
        }
    }
}

主要方法將在MSIL中:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 2
    .locals init (
        [0] class ConsoleApplication3.Example example,
        [1] bool CS$4$0000)
    L_0000: nop 
    L_0001: newobj instance void ConsoleApplication3.Example::.ctor()
    L_0006: stloc.0 
    L_0007: nop 
    L_0008: nop 
    L_0009: leave.s L_001b
    L_000b: ldloc.0 
    L_000c: ldnull 
    L_000d: ceq 
    L_000f: stloc.1 
    L_0010: ldloc.1 
    L_0011: brtrue.s L_001a
    L_0013: ldloc.0 
    L_0014: callvirt instance void [mscorlib]System.IDisposable::Dispose()
    L_0019: nop 
    L_001a: endfinally 
    L_001b: nop 
    L_001c: ret 
    .try L_0007 to L_000b finally handler L_000b to L_001b
}

即使您是MSIL的新用戶,也可以看到try-finally處理程序和Dispose調用。

是的,你確實以正確的方式使用它。 請注意,雖然在實現IDisposable時實例化並使用它的對象很有用。 這真的是CLR為我們做的一件小事,使代碼更清晰。 VB.Net現在也支持這個聲明。 根據我的知識,使用try catch塊的closin對象的using語句之間沒有速度差異,但我建議使用try-catch,更干凈的代碼的usins語句,你不會冒險忘記處理對象或因為你沒有沒有例外

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM