在 Powershell 中使用反射 Class

Using Reflection within Powershell Class

晚上好, 我正在 V5 中测试 Powershell 类,但我无法在 Powershell class 中使用反射。举个例子:

class PSHello{
    [void] Zip(){
        Add-Type -Assembly "System.IO.Compression.FileSystem"
        $includeBaseDirectory = $false
        $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
        [System.IO.Compression.ZipFile]::CreateFromDirectory('C:\test', 'c:\test.zip',$compressionLevel ,$includeBaseDirectory)
    }
}
$f = [PSHello]::new()
$f.Zip()

如我们所见,我正在加载程序集,然后使用反射创建目录的 zip。但是,当这是 运行 时,我收到

的错误
Unable to find type [System.IO.Compression.ZipFile].
+ CategoryInfo          : ParserError: (:) [],        ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TypeNotFound

现在,如果我 运行 在 class 之外使用我的 Zip 方法的相同内容,它就可以工作。那么为什么不能在 class 中像这样使用反射?

IIRC class 方法是预编译的,因此后期绑定无法使用 [type] 语法。我想我们需要手动调用 ZipFile 的方法:

class foo {

    static hidden [Reflection.Assembly]$FS
    static hidden [Reflection.TypeInfo]$ZipFile
    static hidden [Reflection.MethodInfo]$CreateFromDirectory

    [void] Zip() {
        if (![foo]::FS) {
            $assemblyName = 'System.IO.Compression.FileSystem'
            [foo]::FS = [Reflection.Assembly]::LoadWithPartialName($assemblyName)
            [foo]::ZipFile = [foo]::FS.GetType('System.IO.Compression.ZipFile')
            [foo]::CreateFromDirectory = [foo]::ZipFile.GetMethod('CreateFromDirectory',
                [type[]]([string], [string], [IO.Compression.CompressionLevel], [bool]))
        }
        $includeBaseDirectory = $false
        $compressionLevel = [IO.Compression.CompressionLevel]::Optimal
        [foo]::CreateFromDirectory.Invoke([foo]::ZipFile,
            @('c:\test', 'c:\test.zip', $compressionLevel, $includeBaseDirectory))
    }

}

$f = [foo]::new()
$f.Zip()