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

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

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

问题

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

与其像下面这样逐个创建实例,我想通过循环动态地创建它们。下面的"classname"值不能用变量($classname)替换,我已经检查过了。有没有适当的方法来实现这个?

  1. [<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?

  1. [<classname>]$instance = [<classname>]::new()

答案1

得分: 3

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

  1. class A {
  2. $prop = 'classA'
  3. }
  4. class B {
  5. $prop = 'classB'
  6. }
  7. class C {
  8. $prop = 'classC'
  9. }
  10. foreach ($i in 'A', 'B', 'C') {
  11. ($i -as [type])::new() # 使用`-as`运算符
  12. ([type] $i)::new() # 强制转换
  13. }

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

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

或者,个人不推荐使用这种方法,但你可以使用New-Object

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

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

  1. class A {
  2. $prop = 'classA'
  3. }
  4. class B {
  5. $prop = 'classB'
  6. }
  7. class C {
  8. $prop = 'classC'
  9. }
  10. foreach ($i in 'A', 'B', 'C') {
  11. ($i -as [type])::new() # with `-as`
  12. ([type] $i)::new() # casting
  13. }

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):

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

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

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

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:

确定