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

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

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?

[<classname>]$instance = [<classname>]::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 = 'classA' 
}
class B {
    $prop = 'classB' 
}
class C {
    $prop = 'classC' 
}

foreach ($i in 'A', 'B', 'C') {
    ($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 = 'A' -as [type]
0..10 | ForEach-Object {
    $classA::new()
}

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

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

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

发表评论

匿名网友

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

确定