如何在PowerShell中从多个类模块创建动态类实例

huangapple go评论105阅读模式
英文:

How to create dynamic class instances from multiple class modules in PowerShell

问题

我有几个类模块(假设为classA、classB等)用于不同的目的。从主文件中,我想要动态地从每个类创建实例。

与其像下面这样逐个创建实例,我想通过循环动态创建它们。下面的 "classname" 值不能被变量 ($classname) 替换,我已经确认过了。有没有合适的方法来完成这个任务?

[<classname>]$instance = [<classname>]::new()
英文:

I have several class modules (let's assume classA, classB and so on) created for different purposes. From the main file, I want to create instance dynamically from each class

Rather than creating instance one by one like below, I want to create them dynamically through a loop. The below "classname" value cannot be replaced by a variable ($classname) as I checked. Any proper method to get this done?

[&lt;classname&gt;]$instance = [&lt;classname&gt;]::new()

答案1

得分: 3

你可以使用-as运算符或者简单地将[type]强制转换为实例化它们,例如:

class A {
    $prop = 'classA' 
}
class B {
    $prop = 'classB' 
}
class C {
    $prop = 'classC' 
}

foreach ($i in 'A', 'B', 'C') {
    ($i -as [type])::new() # 使用 `-as` 运算符
    ([type] $i)::new()     # 强制类型转换
}

假设您将使用这种方法多次实例化,最好将类型缓存在不同的变量中(以class A为例):

$classA = 'A' -as [type]
0..10 | ForEach-Object {
    $classA::new()
}

或者,个人不建议使用这种方法,但您可以使用New-Object

foreach ($i in 'A', 'B', 'C') {
    New-Object $i
}
英文:

You can use the -as operator or simply cast [type] to instantiate them, for example:

class A {
    $prop = &#39;classA&#39; 
}
class B {
    $prop = &#39;classB&#39; 
}
class C {
    $prop = &#39;classC&#39; 
}

foreach ($i in &#39;A&#39;, &#39;B&#39;, &#39;C&#39;) {
    ($i -as [type])::new() # with `-as`
    ([type] $i)::new()     # casting
}

Assuming you will be instantiating many times using this method, it will be preferable to cache the types in different variables (using class A as example):

$classA = &#39;A&#39; -as [type]
0..10 | ForEach-Object {
    $classA::new()
}

Alternatively, personally wouldn't recommend this method, but you can use New-Object:

foreach ($i in &#39;A&#39;, &#39;B&#39;, &#39;C&#39;) {
    New-Object $i
}

huangapple
  • 本文由 发表于 2023年8月9日 12:33:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864601-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定