Python中C#的using语句等价物
可能重复的问题:
在IronPython中,C#的“using”块有什么等价物?
我正在用IronPython编写一些代码,使用了一些可以被释放的.NET对象。我在想有没有什么比较“python风”的方法来处理这个。目前我有很多的finally语句(我想每个语句里也应该检查一下是否为None - 如果构造函数失败了,变量会不会根本不存在呢?)
def Save(self):
filename = "record.txt"
data = "{0}:{1}".format(self.Level,self.Name)
isf = IsolatedStorageFile.GetUserStoreForApplication()
try:
isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
try:
sw = StreamWriter(isfs)
try:
sw.Write(data)
finally:
sw.Dispose()
finally:
isfs.Dispose()
finally:
isf.Dispose()
4 个回答
0
这是你的代码,里面有一些注释:
def Save(self):
filename = "record.txt"
data = "{0}:{1}".format(self.Level,self.Name)
isf = IsolatedStorageFile.GetUserStoreForApplication()
try:
isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
try: # These try is useless....
sw = StreamWriter(isfs)
try:
sw.Write(data)
finally:
sw.Dispose()
finally: # Because next finally statement (isfs.Dispose) will be always executed
isfs.Dispose()
finally:
isf.Dispose()
对于StreamWrite,你可以使用一个with语句(如果你的对象有__enter__和__exit__方法),那么你的代码看起来会像这样:
def Save(self):
filename = "record.txt"
data = "{0}:{1}".format(self.Level,self.Name)
isf = IsolatedStorageFile.GetUserStoreForApplication()
try:
isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
with StreamWriter(isfs) as sw:
sw.Write(data)
finally:
isf.Dispose()
而StreamWriter在它的__exit__方法中有
sw.Dispose()
10
Python 2.6 引入了 with
语句,这个语句的好处是当你离开 with
语句时,它会自动清理一些对象。至于 IronPython 的库是否支持这个功能,我不太确定,但这个功能在 IronPython 中应该是很自然的选择。
重复的问题和权威的回答:在 IronPython 中,C# 的 "using" 块相当于什么?