gpt4 book ai didi

powershell - 为什么 PowerShell 使用双冒号 (::) 来调用 .NET 类的静态方法?

转载 作者:行者123 更新时间:2023-12-04 01:35:06 32 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

8年前关闭。




Improve this question




使用 C++ 风格的双冒号 '::' 是否有任何具体原因?为什么不使用像 c# 这样的简单点?

最佳答案

这是 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 实战,第二版(Kindle 位置 4494-4507)。曼宁出版社。 Kindle版。

关于powershell - 为什么 PowerShell 使用双冒号 (::) 来调用 .NET 类的静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17759447/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com