如何在PowerShell中释放System.Xml.XmlWriter

10

我正在尝试释放XmlWriter对象:

try
{
    [System.Xml.XmlWriter] $writer = [System.Xml.XmlWriter]::Create('c:\some.xml')
}
finally
{
    $writer.Dispose()
}

错误:

方法调用失败,因为[System.Xml.XmlWellFormedWriter]中没有名为'Dispose'的方法。

另一方面:

 $writer -is [IDisposable]
 # True

我应该做什么?

2个回答

11

Dispose方法在System.Xml.XmlWriter类中是受保护的。你应该使用Close方法代替。

$writer.Close

有一个受保护的方法,我该如何在PowerShell中调用它?类型转换不起作用'($writer -as [IDisposable]).Dispose()'。我应该使用.Net Reflection API吗? - alex2k8
调用Close而不是Dispose。Close释放所有资源。 - Michael
你所说的“错误”的 Dispose 是不正确的。他想要的 Dispose 不是 protected,而是显式接口实现!显式接口实现在 PowerShell 中很难调用。但这个 hack 应该可以解决问题:[IDisposable].GetMethod("Dispose").Invoke($writer, @()) - Jeppe Stig Nielsen

8

这里提供一种替代方案:

(get-interface $obj ([IDisposable])).Dispose()

'Get-Interface'脚本可以在这里找到:http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx,并且建议在此响应中使用。

使用“using”关键字,我们得到:

$MY_DIR = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

# http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx
. ($MY_DIR + '\get-interface.ps1')

# A bit modified code from http://blogs.msdn.com/powershell/archive/2009/03/12/reserving-keywords.aspx
function using
{
    param($obj, [scriptblock]$sb)

    try {
        & $sb
    } finally {
        if ($obj -is [IDisposable]) {
            (get-interface $obj ([IDisposable])).Dispose()
        }
    }
}

# Demo
using($writer = [System.Xml.XmlWriter]::Create('c:\some.xml')) {

}

在PowerShell 2.0中使用'using'关键字会得到以下错误提示:该语言版本不支持'using'关键字。 位于第1行,第6个字符:
  • using <<<<
    • CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
    • FullyQualifiedErrorId : ReservedKeywordNotAllowed
- oɔɯǝɹ
你的意思是说这个示例在2.0上无法工作?还是你自己的代码出了问题 - 如果是后者,请注意我在上面的示例中不得不自己定义'using'关键字。 - alex2k8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接