gpt4 book ai didi

c# - 如何在类(class)内共享 IDisposable 资源?

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:26 25 4
gpt4 key购买 nike

我正在编写一些控制台应用程序来在 SQLite 数据库之间移动一些数据。用于连接的类和各种准备好的语句实现了 IDisposable,因此我使用 using block 实例化这些对象,如下所示:

using (SQLiteConnection sqlite_conn = new SQLiteConnection(connectionString))
{
sqlite_conn.Open();
using (SQLiteCommand sqlite_cmd = new SQLiteCommand())
{
sqlite_cmd.Connection = sqlite_conn;
sqlite_cmd.CommandText = "INSERT INTO SOMETHING SOMETHING;";
sqlite_cmd.ExecuteNonQuery();
}
sqlite_conn.Close();
}

但是,我需要能够在一种方法中创建这些连接,然后在其他方法中调用它们。将这些连接存储为实例变量的最干净、最不易混淆的方法是什么?我想确保以智能方式调用它们的 .Dispose() 方法,但看不到确保所有操作都发生在单个 上下文中的好方法使用 block 。

我知道这是一个 C# 新手问题,所以请调整您的答案。如果您有建议的解决方案,请附上代码示例进行说明,我将不胜感激。

编辑:我的用例是一个控制台应用程序。有人传入源和目标连接字符串,控制台应用程序执行操作。我真的会让我的控制台类程序本身像这样实现 IDisposable 吗?:

class Program : IDisposable
{
private SQLiteConnection sourceConnection;
private SQLiteConnection destinationConnection;

public void Dispose()
{
sourceConnection.Dispose();
destinationConnection.Dispose();
}
}

最佳答案

I need to be able to create these connections in one method, and then call them in other methods. What is the cleanest and least confusing way for me to store these connections as instance variables?

在这种情况下,您保存这些实例变量的类本身应该实现 IDisposable,并且在处置时应确保连接也被处置。

此外,当您同时拥有多个 IDisposables 时,您可以这样重写它,将它们分组并减少代码中的嵌套:

using (SQLiteConnection sqlite_conn = new SQLiteConnection(connectionString))
using (SQLiteCommand sqlite_cmd = new SQLiteCommand())
{
sqlite_conn.Open();

sqlite_cmd.Connection = sqlite_conn;
sqlite_cmd.CommandText = "INSERT INTO SOMETHING SOMETHING;";
sqlite_cmd.ExecuteNonQuery();
} // no need to call .Close(): IDisposable normally handles it for you

关于c# - 如何在类(class)内共享 IDisposable 资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/827644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com