在Powershell类中使用反射
晚上好,, 我正在V5中测试Powershell类,无法在Powershell类中使用反射。以下面的例子为例:在Powershell类中使用反射,powershell,reflection,powershell-5.0,Powershell,Reflection,Powershell 5.0,晚上好,, 我正在V5中测试Powershell类,无法在Powershell类中使用反射。以下面的例子为例: class PSHello{ [void] Zip(){ Add-Type -Assembly "System.IO.Compression.FileSystem" $includeBaseDirectory = $false $compressionLevel = [System.IO.Compression.Compressi
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类方法是预编译的,所以后期绑定不能使用[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()