3

今天下午我试图找出一个解决方案,但到目前为止我只取得了部分成功......

这是我的代码:

class Animal {
    [int] $numOfLegs = 0;
    [int] $numOfEyes = 2;

    [scriptblock] $dog = { 
        class Dog { 
            [int] $numOfLegs = 4
            [int] getLegs(){ return $this.numOfLegs; }
            [int] getEyes(){ return $numOfEyes; }
        }

        return [dog]::new()       
     }
}

(Dog 类可以通过这样做来实例化):

$mypetdog = & ([animal]::new().Dog)

基本上,我的想法是尝试让脚本块充当闭包,以便可以调用包含在 Animal 中的每个“子类”定义(并且仍然可以访问它的父范围)。因此,例如,当在 Dog 对象上执行 getEyes() 时,理论上它会返回数字 2。但是这不起作用,因为我认为脚本块无法看到它自己的范围之外(当在类中定义时)。

所以当我这样做时:

$mypetdog.getLegs()

它正确返回 4,但是当我这样做时:

$mypetdog.getEyes()

Powershell 不知道变量 $numOfEyes 是什么,随后由于该变量在类中未定义而引发错误。

有没有人在不使用 add-type 的情况下在 PowerShell 中模拟子类的解决方案?

4

2 回答 2

3

创建 PowerShell 5.0 中的类是为了简化不需要继承的 DSC 资源的开发,因此尚不支持。正如您在下面看到的,他们将继续努力,但没有 ETA,这意味着您可能必须等到 v6+。

9 月预览版的重点是支持通过 PowerShell 类编写 DSC 资源。这不需要继承,所以你是对的,9 月预览版不支持继承

类在没有继承的情况下仍然可以用于许多事情——例如,C 仍然存在并且它仍然没有成员函数,更不用说继承了。

也就是说,我们显然了解继承的重要性。没有关于何时可用的承诺,但这是我们正在努力的事情

资料来源:WMF 博客 - 评论

您可以尝试使用New-Object,$obj.psobject.copy()Add-Member(定义子类的属性和功能)来使某些东西正常工作,就像有人在此处描述的那样

更新:类继承在 PowerShell 5.0 RTM 中可用。例子:

class Vehicle {
    [string]$Make
    [string]$Model
    [string]$Color

}    

class Car : Vehicle {
    [string]$VIN
}

$car = [car]@{
    Make = "Ford"
    Model = "Mustang"
    Color = "Red"
    VIN = "123456"
}
$car


VIN    Make Model   Color
---    ---- -----   -----
123456 Ford Mustang Red  
于 2015-02-01T11:51:24.457 回答
1

继承由“:”运算符以非常简单的方式给出。

class Animal {
[int] $numOfLegs = 0;
[int] $numOfEyes = 2;

  Animal(){} <- Constructor         
 }


class Dog : Animal { 
        [int] $numOfLegs = 4
  Dog(){} <- Constructor of dogs
        [int] getLegs(){ return $this.numOfLegs; }
        [int] getEyes(){ return $numOfEyes; }
    }

 New-Object Dog
于 2015-11-09T08:40:59.000 回答