代码之家  ›  专栏  ›  技术社区  ›  Martin Prikryl

在PowerShell中按名称调用带有可选参数的.NET方法

  •  1
  • Martin Prikryl  · 技术社区  · 7 年前

    我有一个.NET类,有许多可选参数,比如:

    void Method(int one, int two, int three = 0, int four = 0, int five = 0);
    

    five ,不列出参数 three four ?

    在C#,我可以做:

    instance.Method(1, 2, five: 5);
    

    PowerShell有类似的语法吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Mathias R. Jessen    7 年前

    基本上,您需要计算命名参数的相应参数索引,然后用 [type]::Missing 代替要忽略的可选参数 MethodInfo.Invoke() :

    $method = $instance.GetType().GetMethod("Method") # assuming Method has no additional overloads
    $params = @(1, 2, [type]::Missing, [type]::Missing, 5)
    $method.Invoke($instance, $params)
    
    推荐文章