简体   繁体   English

我应该如何在Java中复制C#的'using'语句的功能?

[英]How should I replicate the functionality of C#'s 'using' statement in Java?

I'm converting some C# code to Java and it contains the using statement. 我正在将一些C#代码转换为Java,它包含using语句。 How should I replicate this functionality in Java? 我应该如何在Java中复制此功能? I was going to use a try , catch , finally block but I thought I'd check with you guys first. 我打算trycatchfinally阻止,但我想我先和你们一起检查。

That's correct. 那是对的。 AC# using block is just syntactic sugar for that anyway. 无论如何,AC#using block只是语法糖。 The closest Java equivalent to IDisposable is Closeable . 与IDisposable最接近的Java是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 7添加类似的功能。它将在幕后使用try-finally,并建议创建一个新的Disposable接口(这将是Closeable的超接口) )。

The standard idiom for resource handling in Java is: Java中资源处理的标准习惯是:

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 null s and such. 常见的错误包括尝试共享相同的try语句,异常捕获和后续操作使得与null等混乱。

The Execute Around Idiom can extract constructs like this, although the Java syntax is verbose. 虽然Java语法很冗长,但Execute Around Idiom可以提取这样的结构。

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

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 而且java中的大多数close()抛出异常,所以如果你希望你的代码更像c#,请检查DbUtils.closeQuietly

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM