Reputation: 97
In my last question, Stack Overflow helped me fix an error with my methods, so now I have a class like
class Main
{
[int]$A
[string]$B
[bool]$C
}
class myClass : Main
{
myClass(){
$This.A = 1
$This.B = "Property"
$This.C = $False
}
[void] AM([string]$Argument) {
Write-Host $Argument
$This.C = $True
}
}
Which has the method AM
, but how can I make constructors like
[myClass]::myConstructor()
Upvotes: 0
Views: 48
Reputation: 3112
PowerShell syntax is generally similar to C# syntax since they both use the .NET framework. It seems like you are confusing static operators and constructors.
Constructors are basically the inputs the class could take. For example:
class Main
{
[int]$A
[string]$B
[bool]$C
}
class myClass : Main
{
myClass(){
$This.A = 1
$This.B = "Property"
$This.C = $False
}
[void] AM([string]$Argument) {
Write-Host $Argument
$This.C = $True
}
}
In your class,
myClass(){
$This.A = 1
$This.B = "Property"
$This.C = $False
}
Is the constructor. They contain the properties from the ::new()
static operator (This may have caused your confusing).
A static operator is like a method but with static operators (::
). You define static operators with Static [void]
or a different type depending on the output type you want. Example:
Static [void] AS() {
Write-Host "Test"
}
In a class like
class Main
{
[int]$A
[string]$B
[bool]$C
}
class myClass : Main
{
myClass(){
$This.A = 1
$This.B = "Property"
$This.C = $False
}
[void] AM([string]$Argument) {
Write-Host $Argument
$This.C = $True
}
Static [void] AC() {
Write-Host "Test"
}
}
You can call the static operator with
[myClass]::AS()
with the output
Test
Which you can't do with methods:
PS C:\> [myClass]::AM("Argument")
Method invocation failed because [myClass] does not contain a method named 'AM'.
At line:1 char:1
+ [myClass]::AM()
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Technically static operators are treated as methods but they are different.
Of course you can also have arguments in your static operator as well, they are basically methods just called differently:
class Main
{
[int]$A
[string]$B
[bool]$C
}
class myClass : Main
{
myClass(){
$This.A = 1
$This.B = "Property"
$This.C = $False
}
Static [void] AC([string]$Argument) {
Write-Host $Argument
}
}
and
PS C:\> [myClass]::AC("Test")
Test
PS C:\> [myClass]::AC("Argument")
Argument
Upvotes: 2