[英]Will a SqlConnection() declared before using it in a using() statement still close the connection when done? (C#/SQL Server)
在這樣的情況下:
SqlConnection cn = new SqlConnection(
ConfigurationManager
.ConnectionStrings["AppConnection"]
.ConnectionString
);
using (cn) {...}
即使未在using()
語句中聲明, using( using()
語句是否仍會關閉連接?
類似於這個問題: SqlConnection with a using clause - calling close on the connection
除了我想知道如何使用實際連接,而不是它的副本。
是的,但你不應該這樣做。
using
文檔說(一直在底部):
您可以實例化資源 object,然后將變量傳遞給 using 語句,但這不是最佳做法。 在這種情況下,在控制權離開 using 塊后,object 仍保留在 scope 中,但可能無法訪問其非托管資源。 換句話說,它不再完全初始化。 如果您嘗試在 using 塊之外使用 object,則可能會引發異常。 為此,最好在using語句中實例化object,並將其scope限制在using塊中。
var reader = new StringReader(manyLines); using (reader) {... } // reader is in scope here, but has been disposed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.