IDisposable metaphor in Java?

后端 未结 6 1199
滥情空心
滥情空心 2021-02-19 13:44

As a java developer getting into .NET I\'d like to understand the IDisposable interface. Could somebody please try to explain this and how it differs from what happens in Java?

6条回答
  •  臣服心动
    2021-02-19 13:58

    Basically IDisposable at a high level, combined with the using keyword is giving you syntactical support for what you see as a common Java idiom like this:

       Connection c = null;
       try {
          c = getConnection();
          ....
       } finally {
          if (c != null) {
              c.close();
          }
       }
    

    If Java had a using keyword and an IDisposable interface with a close() method, it might look like this:

       //psudo-Java
       using(Connection c = getConnection()) {
          .....
       }
    

    With the close method being implicitly called at the end of that block. No need for try/finally.

    That being said, IDisposible has a fairly complex contract, and is mainly concerned with freeing unmanaged memory. You have to work hard with Java to have unmanaged memory (basically with JNI and Swing components, you have the concept), but it is much more common in .NET, so there is language support for the concept.

提交回复
热议问题