C#的using语句调用是否将Dispose on out参数?

时间:2018-07-30 19:02:46

标签: c# ado.net

假设我有:

using(DbDataReader reader = getReader("SELECT * FROM Cmds", out DbCommand cmd))
{

}

我在其中编写了一个辅助方法getReader,以获得一个DbDataReader和一个DbCommandusing语句是否在输出参数Dispose上调用cmd?如果没有,那么有没有一种简洁的方法来实现这一目标,而不是像这样:

DbCommand cmd = null;
try
{
    using(DbDataReader reader = getReader("select value from cmds where typeid = 2;", out cmd))
    {

    }
}
finally
{
    cmd?.Dispose();
}

我可以返回包含两个一次性对象的元组吗,还是会混淆using语句?

我查看了MSDN's documentation for C#'s using statement,但没有提及表达式中获得的out参数。

2 个答案:

答案 0 :(得分:6)

  

在这种情况下,using语句调用是否对输出参数cmd进行处理?

不,不是。它仅在Dispose语句括号内直接创建/分配/传递的实例上调用using

您可以使用多个using语句,并像这样堆叠它们。

using(DbDataReader reader = getReader("SELECT * FROM Cmds", out DbCommand cmd))
using(cmd)
{

}

还请注意,在第一个using语句之后紧接着没有打开/关闭括号,这减少了代码缩进,并使得在第二个{处理之后cmd无法引用{1}}语句。

答案 1 :(得分:1)

您可以编写一个简单的IDisposable包装器类并返回:

public sealed class DbData: IDisposable
{
    public DbData(DbDataReader reader, DbCommand command)
    {
        Reader  = reader;
        Command = command;
    }

    public void Dispose()
    {
        Reader .Dispose();
        Command.Dispose();
    }

    public DbDataReader Reader  { get; }
    public DbCommand    Command { get; }
}

然后您的GetReader()将返回DbData

public DbData GetReader(string sql)
{
    DbDataReader reader  = ...;
    DbCommand    command = ...;

    return new DbData(reader, command);
}

然后您可以将其与using一起使用。

using (var result = GetReader("SELECT * FROM Cmds"))
{
    // Do something with result.Command and result.Reader
}