我应该如何复制 C# 的“使用”功能? Java 中的声明?

发布于 2024-09-07 21:55:45 字数 155 浏览 2 评论 0原文

我正在将一些 C# 代码转换为 Java,它包含 using 语句。我应该如何在 Java 中复制此功能?我本来打算使用 trycatchfinally 块,但我想我应该先和你们确认一下。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无所的.畏惧 2024-09-14 21:55:45

这是正确的。无论如何,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).

十级心震 2024-09-14 21:55:45

Java 中资源处理的标准习惯用法是:

final Resource resource = acquire();
try {
    use(resource);
} finally {
    resource.dispose();
}

常见错误包括尝试共享相同的 try 语句并进行异常捕获,并随后将 null 弄得一团糟等等。

Execute around Idiom 可以提取这样的构造,尽管 Java 语法很冗长。

executeWith(new Handler() { public void use(Resource resource) {
    ...
}});

The standard idiom for resource handling in Java is:

final Resource resource = acquire();
try {
    use(resource);
} finally {
    resource.dispose();
}

Common mistakes include trying to share the same try statement with exception catching and following on from that making a mess with nulls and such.

The Execute Around Idiom can extract constructs like this, although the Java syntax is verbose.

executeWith(new Handler() { public void use(Resource resource) {
    ...
}});
扮仙女 2024-09-14 21:55:45

不要忘记空检查!
也就是说

using(Reader r = new FileReader("c:\test")){
    //some code here
}

应该翻译成类似

Reader r = null;
try{
    //some code here
}
finally{
    if(r != null){
         r.close()
    }
}

java 中的最 close() 抛出异常,所以检查
DbUtils.closeQuietly 如果你希望你的代码更像c#

Don't forget the null checking!
That is to say

using(Reader r = new FileReader("c:\test")){
    //some code here
}

should be translated to something like

Reader r = null;
try{
    //some code here
}
finally{
    if(r != null){
         r.close()
    }
}

And also most close() in java throw exceptions, so check
DbUtils.closeQuietly if you want your code to be more c# like

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文