Powershell:如何将Array的引用从Powershell传递给C#函数

时间:2017-07-18 15:21:42

标签: c# arrays powershell pass-by-reference

我坚持将从Powershell的Array传递给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

1 个答案:

答案 0 :(得分:0)

您无法加载这样的dll文件。你必须这样做:

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

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

[SAMPLEAPI.Sample]::new()

希望有所帮助