Is there any specific reason to use c++ style of double colon '::' ? Why not use a simple dot like c#?
By using the double-colon operator, you remove this ambiguity. Other languages get around this ambiguity by using the typeof() operator. Using typeof() in this example, typeof(My Module). Module retrieves the instance property on the Type object and MyModule.
To call a static method or property, use the name of the class in brackets, then two colons, then the name of the property or method you want to call. In fact, you've already done this in creating a new instance of a class when you used [Twitterer]::new() .
Two colons (::) are used in C++ as a scope resolution operator. This operator gives you more freedom in naming your variables by letting you distinguish between variables with the same name.
To call a static method, we use the name of the class in brackets, followed by two colons, then the name of the static method. In PowerShell, to call a method you always have to use parenthesis after the name of the method even if it takes no parameters.
This is a question for Windows PowerShell in Action.
The :: operator is the static member accessor. Whereas the dot operator retrieved instance members, the double-colon operator accesses static members on a class, as is the case with the join method in the example at the end of the last section. The left operand to the static member accessor is required to be a type—either a type literal or an expression returning a type as you see here:
PS (1) > $t = [string] PS (2) > $t::join('+',(1,2,3)) 1+2+3 PS (3) >
The language design team chose to use a separate operator for accessing static methods because of the way static methods are accessed. Here’s the problem. If you had a type MyModule with a static property called Module, then the expression
[MyModule].Module
is ambiguous. This is because there’s also an instance member Module on the System.Type instance representing the type MyModule. Now you can’t tell if the “Module” instance member on System.Type or the “Module” static member on MyModule should be retrieved. By using the double-colon operator, you remove this ambiguity.
Note
Other languages get around this ambiguity by using the typeof() operator. Using typeof() in this example, typeof(My Module).Module retrieves the instance property on the Type object and MyModule.Module retrieves the static property implemented by the MyModule class.
Bruce Payette (2011-08-02 16:22:31.490000-05:00). Windows PowerShell in Action, Second Edition (Kindle Locations 4494-4507). Manning Publications. Kindle Edition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With