我有一个连接到数据库并检索数据表的 SQL 类。我知道 SqlConnection 必须在完成后处理。我知道这可以使用块来完成,但是将调用放在此类的析构函数中using
是否也可以接受?Dispose()
这是我的代码:
public class SQLEng
{
//Connection String Property
//Must be set to establish a connection to the database
public string ConnectionString{ get; set; }
SqlConnection _Conn;
//Overridden Constructor enforcing the Connection string to be set when created
public SQLEng(string connectionString)
{
ConnectionString = connectionString;
_Conn = new SqlConnection(connectionString);
}
//ensure the SqlConnection is disposed when destructing this object
public ~SQLEng()
{
_Conn.Dispose();
}
//various other methods to get datatables etc...
}
基本上我希望有一个类变量SqlConnection,而不是在每个访问数据库的方法中实例化SqlConnection。这是声音练习吗?