我怎么可能知道SQLcommand是否正确处理?

时间:2014-02-10 08:35:19

标签: c# dispose sqlcommand

如何正确处理SQL命令?

我的问题是我的代码总是返回false,因为我的sqlcommand不等于null

我怎样才能解决这个问题?

这是我的代码:

private SqlCommand Command()
    {
        cmd = new SqlCommand(QueryStr, Connection);
        cmd.StatementCompleted += new StatementCompletedEventHandler(cmd_StatementCompleted);
        return cmd;
    }

    private void cmd_StatementCompleted(object sender, StatementCompletedEventArgs e)
    {
        ((SqlCommand)sender).Dispose();
    }

    public object GetScalarResult()
    {
        Command();

        cmd.CommandType = CommandType;

        con.Open();

        return cmd.ExecuteScalar();
    }

    public bool IsDisposedChecker()
    {
        if (cmd == null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

我的IsDisposedChecker函数总是返回false,这意味着sqlcommand没有正确处理?

1 个答案:

答案 0 :(得分:1)

Dispose() 将指针重置为null。所以ISDisposedChecker函数不能这样工作..

Dispose不是析构函数..


我不会实现dispose-checker,如果你想返回SqlCommand,我会把Dispose责任放到调用方法中。

private SqlCommand Command()
{
    cmd = new SqlCommand(QueryStr, Connection);
    return cmd;
}

private void Test()
{
    // a using block is very safe, it will dispose the command 
    // even when exceptions are thrown.
    using(SqlCommand command = Command())
    {
        // do your thing....
    }
}