gpt4 book ai didi

powershell - 在 Powershell 类中使用反射

转载 作者:行者123 更新时间:2023-12-02 23:41:12 25 4
gpt4 key购买 nike

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

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

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

最佳答案

IIRC 类方法是预编译的,所以后期绑定(bind)不能使用 [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()

关于powershell - 在 Powershell 类中使用反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42013970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com