2017-02-02 11 views
1

晚上好, 我正在測試V5中的Powershell類,我無法在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 

的錯誤,如果我現在運行它的工作原理類以外我郵編方法相同的內容。那麼爲什麼Reflection不能在課堂內像這樣使用?

回答

2

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

強大有趣的,謝謝你的問題 – jladd

+0

調用表達式的答案和解釋可能是一個簡單的解決方案... – wOxxOm