I've tried to work out a solution this afternoon, but I've only had partial success so far...
Here is my code:
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()
}
}
(The Dog class can be instantiated by doing this):
$mypetdog = & ([animal]::new().Dog)
Basically, my idea was to try to get scriptblocks to act as closures, so that each 'subclass' definition contained within Animal could be invoked (and still have access to it's parent scope). So for example, when getEyes() is executed on the Dog object, it would in theory return the number 2. However this didn't work because I think that the scriptblock cannot see outside its own scope (when defined within a class).
So when I do this:
$mypetdog.getLegs()
it correctly returns 4, but when I do this:
$mypetdog.getEyes()
Powershell has no idea what the variable $numOfEyes is and subsequently throws an error because the variable is undefined within the class.
Does anyone have a solution to imitating subclasses in PowerShell without using add-type?
class tree{class node{}}, where a node is not a specialized type of tree, but this specific type of node by itself has no meaning other than within the context of the parent tree class.