2017-07-18 56 views
1

我堅持從Powershell的數組傳遞引用到C#函數,它將參數作爲數組。Powershell:如何將數組從Powershell的引用傳遞到C#函數

我的C#項目是這樣的

namespace SAMPLEAPI 
{ 

    public class TestFunction 
    { 
     public int a; 

     public String b; 
    } 
    public class Sample 
    { 
     public int Test(out TestFunction[] tests) 
     { 
      tests = new TestFunction[2]; 
      tests[0].a = 1; 
      tests[1].a = 2; 
      tests[0].b = "dummy1"; 
      tests[1].b = "dummy2"; 
      return 1; 
     } 
    } 
} 

我編了以上項目SAMPLEAPI.dll,並試圖調用這個函數在PowerShell中

PowerShell腳本:

Import-Module .\SAMPLEAPI.dll 
$testArray = [SAMPLEAPI.TestFunction[]] 
$test = [SAMPLEAPI.Sample]::new() 
$test.Test([ref] $testArray) 

我收到以下異常

Exception calling "Test" with "1" argument(s): "Cannot convert the 
"SAMPLEAPI.TestFunction[]" value of type 
"System.RuntimeType" to type "SAMPLE.TestFunction[]"." 
At line:1 char:1 
+ $test.Test([ref] $a) 
+ ~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : PSInvalidCastException 
+0

'$ testArray = $ null' – PetSerAl

回答

0

你不能像這樣加載一個dll文件。你必須這樣做:

[Reflection.Assembly]::LoadFile(".\SAMPLEAPI.dll") 

然後你可以使用所有的方法:

[SAMPLEAPI.Sample]::new() 

希望它可以幫助

+0

問題不加載DLL作爲這樣的..我能夠訪問其他方法的C#..但它是一個很好的建議,雖然.. 例外是在行 $ test.Test([ref] $ testArray) –