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

回眸只為那壹抹淺笑 提交于 2019-11-26 23:13:49

问题


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

using (var something = new ClassThatImplementsIDisposable())
{
  // stuff happens here
}

回答1:


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

with ClassThatImplementsIDisposable() as something:
    pass



回答2:


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




回答3:


With statement. For example:

with open("/temp/abc") as f:
    lines = f.readlines()



回答4:


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()
    ...



回答5:


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.



来源:https://stackoverflow.com/questions/1757296/what-is-the-equivalent-of-the-c-sharp-using-block-in-ironpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!