处置已实例化为方法参数c#的对象 [英] Dispose object that has been instantiated as method parameter c#

查看:197
本文介绍了处置已实例化为方法参数c#的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

private static readonly string ConnectionString = "Dummy";
public static SqlConnection GetConnection()
{
    SqlConnection Connection = new SqlConnection(ConnectionString);
    return Connection;
}

public static SqlDataAdapter GetDataAdapter(string Query)
{
    SqlDataAdapter Adapt = new SqlDataAdapter(Query, GetConnection());
    return Adapt;
}

  • 如何处理将GetConnection()作为参数传递给SqlDataAdapter构造函数时实例化的SqlConnection对象?
  • 当我在名为GetDataAdapter()的方法中处理我的Adapt对象时,它会自动处理吗?
  • 如果无法处理,您建议如何进行处理?
  • 感谢您的帮助.

    推荐答案

    说明

    如果处置SqlDataAdapter,它也不会处置SqlConnection,因为不清楚是否要再次使用该连接.您必须更改设计才能完成此任务.

    Description

    If you dispose your SqlDataAdapter it does not dispose the SqlConnection too because its not clear if you want to use the connection again. You have to change your design to get this done.

    我建议将SqlConnection传递给GetDataAdapter函数.

    static void Main(string[] args)
    { 
        using (SqlConnection connection = GetConnection()) 
        {
            using (SqlDataAdapter adapter = GetDataAdapter("YourQuery", connection)) 
            {
    
            }
            // SqlDataAdapter is disposed
        }
        // SqlConnection is disposed
    }
    
    private static readonly string ConnectionString = "Dummy";
    public static SqlConnection GetConnection()
    {
        SqlConnection Connection = new SqlConnection(ConnectionString);
        return Connection;
    }
    
    public static SqlDataAdapter GetDataAdapter(string Query, SqlConnection connection)
    {
        SqlDataAdapter Adapt = new SqlDataAdapter(Query, connection);
        return Adapt;
    }
    

    这篇关于处置已实例化为方法参数c#的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆