在 Powershell 中使用名称参数构造函数创建对象

Creating Object with name parameters constructor in Powershell

我有 C# 构造函数

class A {
   public A (name="",version=""){
     //do something
   }
}

在Powershell中导入了相应的DLL。 我想通过传递命名参数来创建 A 对象。

$a = New-Object ABC.XYZ.A -ArgumentList @()  //pass named params

我找不到 doc/example 来用 constructor which takes optional named parameters [there are around 20 params] 创建对象。

我认为这是不可能的,但您可以通过使用 20 个参数从 class 派生来解决它。见下文

$Source = @"
namespace DontCare
{
    /**/
    public class TheCrazyClassWith20parametersCtor
    {
        public TheCrazyClassWith20parametersCtor(/* 20 named parameters here*/)
        {}
    }

    public class MyWrapper : TheCrazyClassWith20parametersCtor
    {
        public MyWrapper(int param1, string param2)
        : base(
            /* use named parameters here*/
        )
        {} 
    }
}
"@

Add-Type -TypeDefinition $Source -Language CSharp

New-Object -TypeName DontCare.MyWrapper -ArgumentList 42,"Hi!"

HTH