代码之家  ›  专栏  ›  技术社区  ›  Mark Heath

Python等价于C#的using语句[重复]

  •  5
  • Mark Heath  · 技术社区  · 14 年前

    可能重复:
    What is the equivalent of the C# “using” block in IronPython?

    我正在使用一些一次性的.NET对象编写一些IronPython,并想知道是否有一种很好的“pythonic”方法来实现这一点。目前我有一堆finally语句(我想每个语句中也应该有一个都不存在的检查——或者如果构造函数失败了变量就不存在了?)

    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 回复  |  直到 7 年前
        1
  •  6
  •   Community Sam Holder    7 年前

    Python2.6引入了 with 具有 陈述。我不知道IronPython库是否支持它,但这是自然的。

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

        2
  •  1
  •   Damian Schenkelman    14 年前

    我想你在找 with statement . 更多信息 here

        3
  •  0
  •   Daniel Roseman    14 年前

    如果我理解正确的话,它看起来相当于 with 陈述。如果类定义了上下文管理器,则它们将在with块之后自动调用。

        4
  •  0
  •   kriss    14 年前

    您的代码带有一些注释:

    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 statent(如果对象为 __ 进入 __ 出口 __

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

    和他的流线型作家 __ __ 方法有

    sw.Dispose()