【问题标题】:string array inside object array in PowershellPowershell中对象数组内的字符串数组
【发布时间】:2022-10-19 21:37:07
【问题描述】:

我试图通过 powershell 从 c# dll 调用一个函数,它需要一个对象数组作为参数,我需要在其中传递字符串,但我不知道如何。

我需要做什么:

C#版本:

printCustom(new object[] {new string[] {"hello", "its", "working"}});

我需要从powershell调用这个函数但是如何传递参数?

printCustom([object[]]@(//now?//));

谢谢。

【问题讨论】:

  • printCustom 是静态方法还是实例方法?
  • printCustom 是静态的

标签: c# powershell


【解决方案1】:

使用一元数组运算符 , 将可枚举类型包装在数组中 - 这将防止 PowerShell 在您构建将实际传递给方法的数组时解开字符串数组:

[TargetType]::printCustom(@(,'hello its working'.Split()))

让我们测试一下:

# Generate test function that takes an array and expects it to contain string arrays

Add-Type @'
using System;

public class TestPrintCustom
{
  public static void printCustom(object[] args)
  {
    foreach(var arg in args){
      foreach(string s in (string[])arg){
        Console.WriteLine(s);
      }
    }
  }
}
'@

[TestPrintCustom]::printCustom(@(,"hello its working".Split()))

正如预期的那样,打印:

hello
its
working

【讨论】:

  • 好吧,这有点奇怪,我正在尝试你的方式,但显然这些函数不再被调用,没有错误..
  • @root823746374 您能否用printCustom 方法的定义更新您的问题?
  • 好的,我找到了一种让它工作的方法。解决方案是在创建数组之前添加 [object[]]。所以:([object[]]@(,'hello its working'.Split()))
  • 只是要知道,如果我想在不使用单个字符串的情况下传递字符串,然后 split() 我应该怎么做?
  • @root823746374 当然,它只是有点混乱/不可读:[TestPrintCustom]::printCustom(@(,[string[]]@('a','b','c')))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
相关资源
最近更新 更多