是否可以在powershell v5中创建子类?
今天下午我试图想出一个解决办法,但到目前为止我只取得了部分成功 这是我的密码:是否可以在powershell v5中创建子类?,powershell,powershell-5.0,Powershell,Powershell 5.0,今天下午我试图想出一个解决办法,但到目前为止我只取得了部分成功 这是我的密码: class Animal { [int] $numOfLegs = 0; [int] $numOfEyes = 2; [scriptblock] $dog = { class Dog { [int] $numOfLegs = 4 [int] getLegs(){ return $this.numOfLegs; }
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类):
基本上,我的想法是尝试让scriptblocks充当闭包,以便可以调用包含在Animal中的每个“子类”定义(并且仍然可以访问它的父范围)。例如,当对Dog对象执行getEyes()时,理论上它将返回数字2。但是,这不起作用,因为我认为scriptblock无法看到自己范围之外的内容(在类中定义时)
所以当我这样做的时候:
$mypetdog.getLegs()
它正确地返回4,但当我这样做时:
$mypetdog.getEyes()
Powershell不知道变量$numofees是什么,随后抛出一个错误,因为该变量在类中未定义
有没有人可以在不使用add type的情况下模仿PowerShell中的子类?PowerShell 5.0中的类是为了简化不需要继承的DSC资源的开发而创建的,因此目前还不支持这种方法。正如您在下面看到的,他们会处理它,但是没有ETA,这意味着您可能需要等到v6+之后 9月份预览的重点是编写DSC 通过PowerShell类获取资源。这不需要继承,, 因此您是正确的,继承在9月份不受支持 预览 类对于许多没有继承的事情仍然有用——例如 示例C还很活跃,但仍然没有成员 函数,更不用说继承了 也就是说,我们显然理解继承的重要性。不 承诺何时提供,但这是我们的承诺 处理 资料来源: 您可以尝试使用
新对象
、$obj.psobject.copy()
和添加成员
(以定义子类的属性和函数),如有人所述
更新:类继承在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
继承由“:”运算符以非常简单的方式给出
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
类动物{
[int]$numOfLegs=0;
[int]$numofees=2;
动物(){}感谢@Frode F.-是的,我有一点直觉,这可能是微软正在考虑的,但我没有看到这个评论…希望在v6中有类似于“extends”或“implements”关键字的东西,这样就可以编程到接口,并在我们需要/想要的时候确保类型安全…RobertW已经阅读了一篇文章dded这一点,但我已经用RTM结果更新了我的答案(多亏了一位对此进行了投票的人,所以我可以更新我的答案):-)你的问题是关于继承类而不是子类;子类应该是另一个类中的类,比如类树{class node{}
,其中节点不是特殊类型的树,但这种特定类型的节点本身除了在父树类的上下文中之外没有其他意义。
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