英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论