【问题标题】:Powershell: How to pass reference of Array from Powershell to C# FunctionPowershell:如何将数组的引用从 Powershell 传递给 C# 函数
【发布时间】:2017-12-23 13:40:52
【问题描述】:

我坚持将 Array 的引用从 Powershell 传递到 C# 函数,该函数将 Out 参数作为数组。

我的 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

【问题讨论】:

  • $testArray = $null

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


【解决方案1】:

你不能像那样加载一个 dll 文件。你必须这样做:

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

那么你就可以使用所有的方法了:

[SAMPLEAPI.Sample]::new()

希望对你有帮助

【讨论】:

  • 问题不在于这样加载 Dll..我能够访问 C# 的其他方法..但这是一个很好的建议.. 例外是 $test.Test( [参考] $testArray)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2010-10-01
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多