我应该如何复制 C# 的“使用”功能? Java 中的声明?
我正在将一些 C# 代码转换为 Java,它包含 using
语句。我应该如何在 Java 中复制此功能?我本来打算使用 try
、catch
、finally
块,但我想我应该先和你们确认一下。
I'm converting some C# code to Java and it contains the using
statement. How should I replicate this functionality in Java? I was going to use a try
, catch
, finally
block but I thought I'd check with you guys first.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是正确的。无论如何,AC# using block 只是语法糖。与 IDisposable 最接近的 Java 等效项是
可关闭
。有一个提案(已部分提交),名为 自动资源管理,用于向Java 7添加类似的功能。它将在幕后使用try-finally,并建议创建一个新的Disposable接口(这将是Closeable的超级接口)。
That's correct. A C# using block is just syntactic sugar for that anyway. The closest Java equivalent to IDisposable is
Closeable
.There is a proposal (which is partially committed already), called Automatic Resource Management, for adding similar functionality to Java 7. It would use try-finally behind the scenes, and proposes creating a new Disposable interface (which would be a superinterface of Closeable).
Java 中资源处理的标准习惯用法是:
常见错误包括尝试共享相同的
try
语句并进行异常捕获,并随后将null
弄得一团糟等等。Execute around Idiom 可以提取这样的构造,尽管 Java 语法很冗长。
The standard idiom for resource handling in Java is:
Common mistakes include trying to share the same
try
statement with exception catching and following on from that making a mess withnull
s and such.The Execute Around Idiom can extract constructs like this, although the Java syntax is verbose.
不要忘记空检查!
也就是说
应该翻译成类似
java 中的最 close() 抛出异常,所以检查
DbUtils.closeQuietly 如果你希望你的代码更像c#
Don't forget the null checking!
That is to say
should be translated to something like
And also most close() in java throw exceptions, so check
DbUtils.closeQuietly if you want your code to be more c# like