在 Powershell 中,`[Math].GetMethods()` 与 [Math]::<method_name> 形式的方法有何不同?

In Powershell, how does `[Math].GetMethods()` differ from methods in form of [Math]::<method_name>?

我最近学习了一种新方法 [Math].GetMethods() returns class 拥有的所有方法。这让我感到困惑,因为我认为 PowerShell 中 class 的所有静态方法都必须使用静态成员运算符 ::[Math]::<method_name> 的形式调用。而且没有[Math]::GetMethods().

这样的方法

你能帮忙澄清一下这个困惑吗? [Math].<method_name>[Math]::<method_name> 有什么区别? 谢谢。

这里::用于调用对象的静态方法。如果将变量设置为对象的实例,则 . 可用于调用方法。喜欢:

# static methods
PS C:\Users\Administrator> [system.diagnostics.process] | gm -static


   TypeName: System.Diagnostics.Process

Name               MemberType Definition
----               ---------- ----------
EnterDebugMode     Method     static void EnterDebugMode()
Equals             Method     static bool Equals(System.Object objA, System.Object objB)
GetCurrentProcess  Method     static System.Diagnostics.Process GetCurrentProcess()
GetProcessById     Method     static System.Diagnostics.Process GetProcessById(int processId, string machineName), s...
GetProcesses       Method     static System.Diagnostics.Process[] GetProcesses(), static System.Diagnostics.Process[...
GetProcessesByName Method     static System.Diagnostics.Process[] GetProcessesByName(string processName), static Sys...
LeaveDebugMode     Method     static void LeaveDebugMode()
new                Method     System.Diagnostics.Process new()
ReferenceEquals    Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
Start              Method     static System.Diagnostics.Process Start(string fileName, string userName, securestring...

# other methods
PS C:\Users\Administrator> [system.diagnostics.process] | gm


   TypeName: System.RuntimeType

Name                           MemberType Definition
----                           ---------- ----------
AsType                         Method     type AsType()
Clone                          Method     System.Object Clone(), System.Object ICloneable.Clone()
Equals                         Method     bool Equals(System.Object obj), bool Equals(type o), bool _MemberInfo.Equa...
FindInterfaces                 Method     type[] FindInterfaces(System.Reflection.TypeFilter filter, System.Object f...
FindMembers                    Method     System.Reflection.MemberInfo[] FindMembers(System.Reflection.MemberTypes m...
GetArrayRank                   Method     int GetArrayRank(), int _Type.GetArrayRank()
GetConstructor                 Method     System.Reflection.ConstructorInfo GetConstructor(System.Reflection.Binding...
GetConstructors                Method     System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.Bind...
GetCustomAttributes            Method     System.Object[] GetCustomAttributes(bool inherit), System.Object[] GetCust...
GetCustomAttributesData        Method     System.Collections.Generic.IList[System.Reflection.CustomAttributeData] Ge...
GetDeclaredEvent               Method     System.Reflection.EventInfo GetDeclaredEvent(string name)
GetDeclaredField               Method     System.Reflection.FieldInfo GetDeclaredField(string name)
GetDeclaredMethod              Method     System.Reflection.MethodInfo GetDeclaredMethod(string name)
GetDeclaredMethods             Method     System.Collections.Generic.IEnumerable[System.Reflection.MethodInfo] GetDe...
GetDeclaredNestedType          Method     System.Reflection.TypeInfo GetDeclaredNestedType(string name)
GetDeclaredProperty            Method     System.Reflection.PropertyInfo GetDeclaredProperty(string name)
GetDefaultMembers              Method     System.Reflection.MemberInfo[] GetDefaultMembers(), System.Reflection.Memb...
GetElementType                 Method     type GetElementType(), type _Type.GetElementType()
GetEnumName                    Method     string GetEnumName(System.Object value)
GetEnumNames                   Method     string[] GetEnumNames()
GetEnumUnderlyingType          Method     type GetEnumUnderlyingType()
GetEnumValues                  Method     array GetEnumValues()
GetEvent                       Method     System.Reflection.EventInfo GetEvent(string name, System.Reflection.Bindin...
GetEvents                      Method     System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bin...
GetField                       Method     System.Reflection.FieldInfo GetField(string name, System.Reflection.Bindin...
GetFields                      Method     System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bin...
GetGenericArguments            Method     type[] GetGenericArguments()
GetGenericParameterConstraints Method     type[] GetGenericParameterConstraints()
GetGenericTypeDefinition       Method     type GetGenericTypeDefinition()
GetHashCode                    Method     int GetHashCode(), int _MemberInfo.GetHashCode(), int _Type.GetHashCode()
GetIDsOfNames                  Method     void _MemberInfo.GetIDsOfNames([ref] guid riid, System.IntPtr rgszNames, u...
GetInterface                   Method     type GetInterface(string fullname, bool ignoreCase), type GetInterface(str...
GetInterfaceMap                Method     System.Reflection.InterfaceMapping GetInterfaceMap(type ifaceType), System...
GetInterfaces                  Method     type[] GetInterfaces(), type[] _Type.GetInterfaces()
GetMember                      Method     System.Reflection.MemberInfo[] GetMember(string name, System.Reflection.Me...
GetMembers                     Method     System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags b...
GetMethod                      Method     System.Reflection.MethodInfo GetMethod(string name, System.Reflection.Bind...
GetMethods                     Method     System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags b...
GetNestedType                  Method     type GetNestedType(string fullname, System.Reflection.BindingFlags binding...
GetNestedTypes                 Method     type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr), type[] ...
GetObjectData                  Method     void GetObjectData(System.Runtime.Serialization.SerializationInfo info, Sy...
GetProperties                  Method     System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFl...
GetProperty                    Method     System.Reflection.PropertyInfo GetProperty(string name, System.Reflection....
GetType                        Method     type GetType(), type _MemberInfo.GetType(), type _Type.GetType()
GetTypeInfo                    Method     void _MemberInfo.GetTypeInfo(uint32 iTInfo, uint32 lcid, System.IntPtr ppT...
GetTypeInfoCount               Method     void _MemberInfo.GetTypeInfoCount([ref] uint32 pcTInfo), void _Type.GetTyp...
Invoke                         Method     void _MemberInfo.Invoke(uint32 dispIdMember, [ref] guid riid, uint32 lcid,...
InvokeMember                   Method     System.Object InvokeMember(string name, System.Reflection.BindingFlags bin...
IsAssignableFrom               Method     bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo), bool IsAssigna...
IsDefined                      Method     bool IsDefined(type attributeType, bool inherit), bool ICustomAttributePro...
IsEnumDefined                  Method     bool IsEnumDefined(System.Object value)
IsEquivalentTo                 Method     bool IsEquivalentTo(type other)
IsInstanceOfType               Method     bool IsInstanceOfType(System.Object o), bool _Type.IsInstanceOfType(System...
IsSubclassOf                   Method     bool IsSubclassOf(type type), bool _Type.IsSubclassOf(type c)
MakeArrayType                  Method     type MakeArrayType(), type MakeArrayType(int rank)
MakeByRefType                  Method     type MakeByRefType()
MakeGenericType                Method     type MakeGenericType(Params type[] instantiation)
MakePointerType                Method     type MakePointerType()
ToString                       Method     string ToString(), string _MemberInfo.ToString(), string _Type.ToString()
Assembly                       Property   System.Reflection.Assembly Assembly {get;}
AssemblyQualifiedName          Property   string AssemblyQualifiedName {get;}
Attributes                     Property   System.Reflection.TypeAttributes Attributes {get;}
BaseType                       Property   type BaseType {get;}
ContainsGenericParameters      Property   bool ContainsGenericParameters {get;}
CustomAttributes               Property   System.Collections.Generic.IEnumerable[System.Reflection.CustomAttributeDa...
DeclaredConstructors           Property   System.Collections.Generic.IEnumerable[System.Reflection.ConstructorInfo] ...
DeclaredEvents                 Property   System.Collections.Generic.IEnumerable[System.Reflection.EventInfo] Declar...
DeclaredFields                 Property   System.Collections.Generic.IEnumerable[System.Reflection.FieldInfo] Declar...
DeclaredMembers                Property   System.Collections.Generic.IEnumerable[System.Reflection.MemberInfo] Decla...
DeclaredMethods                Property   System.Collections.Generic.IEnumerable[System.Reflection.MethodInfo] Decla...
DeclaredNestedTypes            Property   System.Collections.Generic.IEnumerable[System.Reflection.TypeInfo] Declare...
DeclaredProperties             Property   System.Collections.Generic.IEnumerable[System.Reflection.PropertyInfo] Dec...
DeclaringMethod                Property   System.Reflection.MethodBase DeclaringMethod {get;}
DeclaringType                  Property   type DeclaringType {get;}
FullName                       Property   string FullName {get;}
GenericParameterAttributes     Property   System.Reflection.GenericParameterAttributes GenericParameterAttributes {g...
GenericParameterPosition       Property   int GenericParameterPosition {get;}
GenericTypeArguments           Property   type[] GenericTypeArguments {get;}
GenericTypeParameters          Property   type[] GenericTypeParameters {get;}
GUID                           Property   guid GUID {get;}
HasElementType                 Property   bool HasElementType {get;}
ImplementedInterfaces          Property   System.Collections.Generic.IEnumerable[type] ImplementedInterfaces {get;}
IsAbstract                     Property   bool IsAbstract {get;}
IsAnsiClass                    Property   bool IsAnsiClass {get;}
IsArray                        Property   bool IsArray {get;}
IsAutoClass                    Property   bool IsAutoClass {get;}
IsAutoLayout                   Property   bool IsAutoLayout {get;}
IsByRef                        Property   bool IsByRef {get;}
IsClass                        Property   bool IsClass {get;}
IsCOMObject                    Property   bool IsCOMObject {get;}
IsConstructedGenericType       Property   bool IsConstructedGenericType {get;}
IsContextful                   Property   bool IsContextful {get;}
IsEnum                         Property   bool IsEnum {get;}
IsExplicitLayout               Property   bool IsExplicitLayout {get;}
IsGenericParameter             Property   bool IsGenericParameter {get;}
IsGenericType                  Property   bool IsGenericType {get;}
IsGenericTypeDefinition        Property   bool IsGenericTypeDefinition {get;}
IsImport                       Property   bool IsImport {get;}
IsInterface                    Property   bool IsInterface {get;}
IsLayoutSequential             Property   bool IsLayoutSequential {get;}
IsMarshalByRef                 Property   bool IsMarshalByRef {get;}
IsNested                       Property   bool IsNested {get;}
IsNestedAssembly               Property   bool IsNestedAssembly {get;}
IsNestedFamANDAssem            Property   bool IsNestedFamANDAssem {get;}
IsNestedFamily                 Property   bool IsNestedFamily {get;}
IsNestedFamORAssem             Property   bool IsNestedFamORAssem {get;}
IsNestedPrivate                Property   bool IsNestedPrivate {get;}
IsNestedPublic                 Property   bool IsNestedPublic {get;}
IsNotPublic                    Property   bool IsNotPublic {get;}
IsPointer                      Property   bool IsPointer {get;}
IsPrimitive                    Property   bool IsPrimitive {get;}
IsPublic                       Property   bool IsPublic {get;}
IsSealed                       Property   bool IsSealed {get;}
IsSecurityCritical             Property   bool IsSecurityCritical {get;}
IsSecuritySafeCritical         Property   bool IsSecuritySafeCritical {get;}
IsSecurityTransparent          Property   bool IsSecurityTransparent {get;}
IsSerializable                 Property   bool IsSerializable {get;}
IsSpecialName                  Property   bool IsSpecialName {get;}
IsUnicodeClass                 Property   bool IsUnicodeClass {get;}
IsValueType                    Property   bool IsValueType {get;}
IsVisible                      Property   bool IsVisible {get;}
MemberType                     Property   System.Reflection.MemberTypes MemberType {get;}
MetadataToken                  Property   int MetadataToken {get;}
Module                         Property   System.Reflection.Module Module {get;}
Name                           Property   string Name {get;}
Namespace                      Property   string Namespace {get;}
ReflectedType                  Property   type ReflectedType {get;}
StructLayoutAttribute          Property   System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute...
TypeHandle                     Property   System.RuntimeTypeHandle TypeHandle {get;}
TypeInitializer                Property   System.Reflection.ConstructorInfo TypeInitializer {get;}
UnderlyingSystemType           Property   type UnderlyingSystemType {get;}

# call a static method with ::
PS C:\Users\Administrator> [system.diagnostics.process]::start('notepad.exe')

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
     28       3      468       2200       0.05   9176   2 notepad

# set variable to instance of an object
PS C:\Users\Administrator> $proc = get-process notepad
PS C:\Users\Administrator> $proc | gm
# list the methods and properties

   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition
----                       ----------     ----------
Handles                    AliasProperty  Handles = Handlecount
Name                       AliasProperty  Name = ProcessName
NPM                        AliasProperty  NPM = NonpagedSystemMemorySize64
PM                         AliasProperty  PM = PagedMemorySize64
SI                         AliasProperty  SI = SessionId
VM                         AliasProperty  VM = VirtualMemorySize64
WS                         AliasProperty  WS = WorkingSet64
Disposed                   Event          System.EventHandler Disposed(System.Object, System.EventArgs)
ErrorDataReceived          Event          System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(System.Objec...
Exited                     Event          System.EventHandler Exited(System.Object, System.EventArgs)
OutputDataReceived         Event          System.Diagnostics.DataReceivedEventHandler OutputDataReceived(System.Obje...
BeginErrorReadLine         Method         void BeginErrorReadLine()
BeginOutputReadLine        Method         void BeginOutputReadLine()
CancelErrorRead            Method         void CancelErrorRead()
CancelOutputRead           Method         void CancelOutputRead()
Close                      Method         void Close()
CloseMainWindow            Method         bool CloseMainWindow()
CreateObjRef               Method         System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                    Method         void Dispose(), void IDisposable.Dispose()
Equals                     Method         bool Equals(System.Object obj)
GetHashCode                Method         int GetHashCode()
GetLifetimeService         Method         System.Object GetLifetimeService()
GetType                    Method         type GetType()
InitializeLifetimeService  Method         System.Object InitializeLifetimeService()
Kill                       Method         void Kill()
Refresh                    Method         void Refresh()
Start                      Method         bool Start()
ToString                   Method         string ToString()
WaitForExit                Method         bool WaitForExit(int milliseconds), void WaitForExit()
WaitForInputIdle           Method         bool WaitForInputIdle(int milliseconds), bool WaitForInputIdle()
__NounName                 NoteProperty   string __NounName=Process
BasePriority               Property       int BasePriority {get;}
Container                  Property       System.ComponentModel.IContainer Container {get;}
EnableRaisingEvents        Property       bool EnableRaisingEvents {get;set;}
ExitCode                   Property       int ExitCode {get;}
ExitTime                   Property       datetime ExitTime {get;}
Handle                     Property       System.IntPtr Handle {get;}
HandleCount                Property       int HandleCount {get;}
HasExited                  Property       bool HasExited {get;}
Id                         Property       int Id {get;}
MachineName                Property       string MachineName {get;}
MainModule                 Property       System.Diagnostics.ProcessModule MainModule {get;}
MainWindowHandle           Property       System.IntPtr MainWindowHandle {get;}
MainWindowTitle            Property       string MainWindowTitle {get;}
MaxWorkingSet              Property       System.IntPtr MaxWorkingSet {get;set;}
MinWorkingSet              Property       System.IntPtr MinWorkingSet {get;set;}
Modules                    Property       System.Diagnostics.ProcessModuleCollection Modules {get;}
NonpagedSystemMemorySize   Property       int NonpagedSystemMemorySize {get;}
NonpagedSystemMemorySize64 Property       long NonpagedSystemMemorySize64 {get;}
PagedMemorySize            Property       int PagedMemorySize {get;}
PagedMemorySize64          Property       long PagedMemorySize64 {get;}
PagedSystemMemorySize      Property       int PagedSystemMemorySize {get;}
PagedSystemMemorySize64    Property       long PagedSystemMemorySize64 {get;}
PeakPagedMemorySize        Property       int PeakPagedMemorySize {get;}
PeakPagedMemorySize64      Property       long PeakPagedMemorySize64 {get;}
PeakVirtualMemorySize      Property       int PeakVirtualMemorySize {get;}
PeakVirtualMemorySize64    Property       long PeakVirtualMemorySize64 {get;}
PeakWorkingSet             Property       int PeakWorkingSet {get;}
PeakWorkingSet64           Property       long PeakWorkingSet64 {get;}
PriorityBoostEnabled       Property       bool PriorityBoostEnabled {get;set;}
PriorityClass              Property       System.Diagnostics.ProcessPriorityClass PriorityClass {get;set;}
PrivateMemorySize          Property       int PrivateMemorySize {get;}
PrivateMemorySize64        Property       long PrivateMemorySize64 {get;}
PrivilegedProcessorTime    Property       timespan PrivilegedProcessorTime {get;}
ProcessName                Property       string ProcessName {get;}
ProcessorAffinity          Property       System.IntPtr ProcessorAffinity {get;set;}
Responding                 Property       bool Responding {get;}
SafeHandle                 Property       Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle {get;}
SessionId                  Property       int SessionId {get;}
Site                       Property       System.ComponentModel.ISite Site {get;set;}
StandardError              Property       System.IO.StreamReader StandardError {get;}
StandardInput              Property       System.IO.StreamWriter StandardInput {get;}
StandardOutput             Property       System.IO.StreamReader StandardOutput {get;}
StartInfo                  Property       System.Diagnostics.ProcessStartInfo StartInfo {get;set;}
StartTime                  Property       datetime StartTime {get;}
SynchronizingObject        Property       System.ComponentModel.ISynchronizeInvoke SynchronizingObject {get;set;}
Threads                    Property       System.Diagnostics.ProcessThreadCollection Threads {get;}
TotalProcessorTime         Property       timespan TotalProcessorTime {get;}
UserProcessorTime          Property       timespan UserProcessorTime {get;}
VirtualMemorySize          Property       int VirtualMemorySize {get;}
VirtualMemorySize64        Property       long VirtualMemorySize64 {get;}
WorkingSet                 Property       int WorkingSet {get;}
WorkingSet64               Property       long WorkingSet64 {get;}
PSConfiguration            PropertySet    PSConfiguration {Name, Id, PriorityClass, FileVersion}
PSResources                PropertySet    PSResources {Name, Id, Handlecount, WorkingSet, NonPagedMemorySize, PagedM...
Company                    ScriptProperty System.Object Company {get=$this.Mainmodule.FileVersionInfo.CompanyName;}
CPU                        ScriptProperty System.Object CPU {get=$this.TotalProcessorTime.TotalSeconds;}
Description                ScriptProperty System.Object Description {get=$this.Mainmodule.FileVersionInfo.FileDescri...
FileVersion                ScriptProperty System.Object FileVersion {get=$this.Mainmodule.FileVersionInfo.FileVersion;}
Path                       ScriptProperty System.Object Path {get=$this.Mainmodule.FileName;}
Product                    ScriptProperty System.Object Product {get=$this.Mainmodule.FileVersionInfo.ProductName;}
ProductVersion             ScriptProperty System.Object ProductVersion {get=$this.Mainmodule.FileVersionInfo.Product...

# call one with .
PS C:\Users\Administrator> $proc.Kill()

GetMethods() 来自 Sysem.Type,所以你根本没有调用 Math 的成员。

当你使用[math]类型加速器时,它会return一个RuntimeType对象。像这样,

[math].gettype()
IsPublic IsSerial Name                     BaseType
-------- -------- ----                     --------
False    True     RuntimeType              System.Reflection.TypeInfo

现在,如果像这样通过成员访问运算符 . 调用 Math class 静态方法,

[math].abs(-42)

Method invocation failed because [System.RuntimeType] does not contain a method named 'abs'.
At line:1 char:1
+ [math].abs(-42)
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MethodNotFound

有一条错误信息。请注意,System.RuntimeType 抱怨 non-existing 方法 abs

要调用Math的静态成员,需要使用静态成员运算符::

[math]::abs(-42)
42