C#通用方法/多态性
发布时间:2020-12-16 00:23:31 所属栏目:百科 来源:网络整理
导读:我有以下用于关闭流的代码. void CloseStream(Stream s){ if (s != null) s.Close();}void CloseStream(HttpWebResponse s){ if (s != null) s.Close();}void CloseStream(StreamReader s){ if (s != null) s.Close();} 代码完美无缺,但我想重构3种方法,如果
我有以下用于关闭流的代码.
void CloseStream(Stream s) { if (s != null) s.Close(); } void CloseStream(HttpWebResponse s) { if (s != null) s.Close(); } void CloseStream(StreamReader s) { if (s != null) s.Close(); } 代码完美无缺,但我想重构3种方法,如果可能的话. void CloseStream(Object obj) { obj.Close(); } 但是我不能做obj.Close()因为Object类没有实现这样的方法. 谢谢你的时间, 解决方法
所有这些’流’都是
disposable,所以使用Dispose()而不是Close():
void CloseStream(IDisposable s) { if (s != null) s.Dispose(); } 还要考虑使用内置的功能.Net Framework – using(StreamReader reader = File.OpenText(path))// create disposable here { // use disposable } 此代码将自动检查一次性是否为空,并在使用块结束时将其丢弃.上面的代码块将编译成: StreamReader reader = File.OpenText(path); try { // use disposable } finally // will be executed even in case of exception { if (reader != null) reader.Dispose(); // internally calls Close() } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- AM3517之SD卡启动盘恢复NAND flash的数据:x-loader(二)
- objective-c – UICollectionViewCell上的手势;怎么处理结果
- 具有$名称的Oracle表
- NoSql之深入浅出redis
- jsonp解决Ajax跨域问题
- c# – 如何用StaticResource的字符串填充List
- 如何将SQLite数据库(dictionary.db文件)与apk文件一起发布
- postgresql – 在Delphi上使用FireDAC从sql表中获取text []
- Xcode 9和Xcode 8一起?
- react-native – undefined不是对象(评估’RootComponent.p