Why does PowerShell use a double colon (: :) to call static methods of the .NET class?

Is there any specific reason to use the C ++ double colon '::' style? Why not use a simple dot like C #?

+7
powershell
source share
1 answer

This is a question for Windows PowerShell in action.

The :: operator is a static access element. While the point is operator-invoked instance members, the double-column operator accesses the static members of the class, as is the case with the join method in the example at the end of the last section. The left operand to a static member requires a type โ€” either a letter type 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 development team decided to use a separate operator for accessing static methods because of how static methods are accessed. This is problem. If you had a MyModule type with a static property called Module, then the expression

[MyModule].Module

is ambiguous. This is because theres is also a member of the Module on instance of the System.Type instance representing the MyModule type. Now you canโ€™t tell if the member of the โ€œModuleโ€ instance in System.Type or the โ€œModuleโ€ static member in MyModule needs to be restored. Using double-colon, you eliminate this ambiguity.

Note

Other languages โ€‹โ€‹get around this ambiguity with the typeof () operator. Using typeof () in this example, typeof (My module) .Module retrieves the instance property of 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.

+20
source share

All Articles