假设我有:
using(DbDataReader reader = getReader("SELECT * FROM Cmds", out DbCommand cmd))
{
}
我在其中编写了一个辅助方法getReader
,以获得一个DbDataReader
和一个DbCommand
。 using
语句是否在输出参数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
参数。
答案 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
}