gpt4 book ai didi

c# - 在 C# 中包装一个不可继承的类

转载 作者:太空狗 更新时间:2023-10-29 21:15:41 26 4
gpt4 key购买 nike

我有一个简单的问题。

我想装饰 SqlDataReader 类,以便在调用 dispose 或 close 方法时我可以同​​时处理隐藏的资源。

SqlDataReader 类不可继承。

我怎样才能做到这一点?我真的不想实现 DbDataReader、IDataReader、IDisposable 和 IDataRecord 接口(interface)

最佳答案

即使您可以从 SqlDataReader 继承也无所谓,因为您无法让 SqlCommand 创建派生类的实例。

当您只是推迟到底层 SqlDataReader 时,在包装器中实现 IDataReader 真的一点也不难。这只是有点耗时,但还算不错。

但是我很好奇,你要配置的资源是连接吗?如果是这样,CommandBehavior 枚举的 CloseConnection 成员可确保在数据读取器关闭时关闭连接。

var reader = command.ExecuteReader(CommandBehavior.CloseConnection);
...
reader.Close(); // also closes connection

请注意,Close/Dispose 在 SqlDataReader 上是同一回事。

最后,这是过去对我很有帮助的最后一个建议。请注意,在下面的松散示例中,您从头到尾都拥有 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

关于c# - 在 C# 中包装一个不可继承的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2004113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com