为什么分配给静态变量的sqlliteconnection被处置?

Why sqlliteconnection assigned to static variables are disposed?

我正在将 sqlliteconnection 对象分配给静态变量并在函数中对其进行初始化。

在某些情况下访问 sqlliteconnection 对象时会抛出 "sqlconnection object is disposed" 异常。据我所知,静态变量仅在应用程序关闭时被释放。

示例代码:

public static SQLLiteConnection sql;

public void OpenConnection()
{
     sql = new SQLLiteConnection ;
     //assign sql lite file path
     sql.Open();
}

public void GetStud()
{
  OpenConnection();
 //writing sqlcommand connection
}
}

您甚至可以在静态对象上调用 Dispose()。它的目的是释放非托管资源(托管资源由GC自动释放)。仅在应用程序关闭后才调用 Dispose。只要没有对此对象的引用,它通常会从终结器方法(由 GC 调用)自动调用。它也在 using 块的末尾调用。

无论如何,静态 SqlConnection 对象不是一个好主意。最好始终使用 "using".

创建新实例
using (var conn = new SQLLiteConnection("connectionstring"))
{
   conn.Open();
}//here is called Dispose()