我有一个简单的问题.
我想装饰SqlDataReader类,以便在调用dispose或close方法时,我可以同时处理隐藏的资源.
SqlDataReader类不可继承.
我怎么能做到这一点?我真的不想实现DbDataReader,IDataReader,IDisposable和IDataRecord接口
即使您可以从SqlDataReader继承也无关紧要,因为您无法使SqlCommand创建派生类的实例.
当您只是推迟到底层的SqlDataReader时,在包装器中实现IDataReader实际上并不难.它只是耗费一点时间而不是那么糟糕.
但我很好奇,你想要的资源是否已经解决了连接问题?如果是这样,CommandBehavior枚举的CloseConnection成员将确保在关闭数据读取器时关闭连接.
var reader = command.ExecuteReader(CommandBehavior.CloseConnection);
...
reader.Close(); // also closes connection
Run Code Online (Sandbox Code Playgroud)
请注意,SqlDataReader上的Close/Dispose是相同的.
最后,这是最后一个在过去对我很好的建议.请注意,在下面的松散示例中,即使您在每个记录处"回放"给调用者,您也可以从头到尾拥有SqlDataReader.
private static IEnumerable<IDataRecord> GetResults(this SqlCommand command) {
using (var myTicket = new MyTicket())
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
yield return reader;
}
}
// the two resources in the using blocks above will be
// disposed when the foreach loop below exits
}
...
foreach (var record in myCommand.GetResults()) {
Console.WriteLine(record.GetString(0));
}
// when the foreach loop above completes, the compiler-generated
// iterator is disposed, allowing the using blocks inside the
// above method to clean up the reader/myTicket objects
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2227 次 |
| 最近记录: |