What is the equivalent of the C# “using” block in IronPython?

前端 未结 5 848
不思量自难忘°
不思量自难忘° 2020-12-06 05:09

What\'s the equivalent of this in IronPython? Is it just a try-finally block?

using (var something = new ClassThatImp         


        
相关标签:
5条回答
  • 2020-12-06 05:26

    There is the with statement: http://www.ironpythoninaction.com/magic-methods.html#context-managers-and-the-with-statement

    with open(filename) as handle:
        data = handle.read()
        ...
    
    0 讨论(0)
  • 2020-12-06 05:40

    IronPython (as of the 2.6 release candidates) supports the with statement, which wraps an IDisposable object in a manner similar to using.

    0 讨论(0)
  • 2020-12-06 05:42

    IronPython supports using IDisposable with with statement, so you can write something like this:

    with ClassThatImplementsIDisposable() as something:
        pass
    
    0 讨论(0)
  • 2020-12-06 05:42

    the using block is in fact the following under the hood:

    try {
      (do something unmanaged here)
    }
    finally {
      unmanagedObject.Dispose();
    }
    

    Hope this helps you understand the logic behind the using statement.

    0 讨论(0)
  • 2020-12-06 05:51

    With statement. For example:

    with open("/temp/abc") as f:
        lines = f.readlines()
    
    0 讨论(0)
提交回复
热议问题