系统相关
首页 > 系统相关> > c# – 在Powershell中使用名称参数构造函数创建对象

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

作者:互联网

我有C#构造函数

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

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

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

我找不到使用构造函数创建对象的doc / example,它使用可选的命名参数[大约有20个参数].

解决方法:

我不认为这是可能的,但你可以通过派生20个参数的类来解决它.请参阅以下内容

$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

标签:c,powershell,named-parameters
来源: https://codeday.me/bug/20190627/1309582.html