C#的using和IDisposable的執行順序

來源:互聯網
上載者:User

做一個測試,這樣一個類,繼承IDisposable,當Dispose方法被調用時,輸出id欄位:

class a : IDisposable

{

    int id;

    public a(int i)

    {

        id = i;

    }

 

    void IDisposable.Dispose()

    {

        Console.WriteLine(id);

    }

}

 

然後:

using (new a(1))

using (new a(2))

using (new a(3))

{ }

 

事實上還可以這樣寫

using (a oa = new a(1), ob = new a(2), oc = new a(3))

{ }

 

不論上面哪種寫法,輸出都是:

3

2

1

可以看出來,最後定義的對象會被最先釋放!

這個在某些時候很有用的,比如多個對象互相有依賴關係,如果不用嵌套using的話:

//MemoryStream在System.IO;

//CryptoStream在System.Security.Cryptography;

 

ICryptoTransform trans;

/* 省略 */

 

//MemoryStream必須定義在前面,因為後面的CryptoStream需要它

var ms = new MemoryStream();

var cs = new CryptoStream(ms, trans, CryptoStreamMode.Read);

 

/* 省略 */

cs.Close();

//MemoryStream.Close必須在後面,因為CryptoStream的Close方法可能會往MemoryStream中

//再次寫入資料,因此MemoryStream必須在CryptoStream結束後再結束

ms.Close();

 

用using的話,看著就舒服多了!

ICryptoTransform trans;

/* 省略 */

 

using (var ms = new MemoryStream())

using (var cs = new CryptoStream(ms, trans, CryptoStreamMode.Read))

{

    /* 省略 */

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.