PowerShell面向对象编程基础知识总结

2019-09-30 16:46:34丽君

对于类和对象而言,我们在PowerShell开发时,更多的关注它的成员,即类的属性和方法。PowerShell中的类和C#一样,有静态成员和实例成员两种。下面分别演示一下:

我们可以通过Get-Member的Static参数来列出类型的静态成员:

PS C:usersplaybow> [int] | Get-Member -Static | Out-String -Width 80

   TypeName: System.Int32

Name            MemberType Definition
----            ---------- ----------
Equals          Method     static System.Boolean Equals(Object objA, Object o...
Parse           Method     static System.Int32 Parse(String s), static System...
ReferenceEquals Method     static System.Boolean ReferenceEquals(Object objA,...
TryParse        Method     static System.Boolean TryParse(String s, Int32& re...
MaxValue        Property   static System.Int32 MaxValue {get;}
MinValue        Property   static System.Int32 MinValue {get;}

我们可以看到,System.Int32上有MaxValue和MinValue两个静态属性,它们指示了System.Int32类型的值域:

PS C:Userssplaybow> [int]::MaxValue
2147483647
PS C:Userssplaybow> [int]::MinValue
-2147483648

如果没有指定Static参数,那么Get-Member会显示对象的实例方法:

PS C:Userssplaybow> [int]::MinValue | Get-Member | Out-String -Width 80

   TypeName: System.Int32

Name        MemberType Definition
----        ---------- ----------
CompareTo   Method     System.Int32 CompareTo(Int32 value), System.Int32 Comp...
Equals      Method     System.Boolean Equals(Object obj), System.Boolean Equa...
GetHashCode Method     System.Int32 GetHashCode()
GetType     Method     System.Type GetType()
GetTypeCode Method     System.TypeCode GetTypeCode()
ToString    Method     System.String ToString(), System.String ToString(IForm...

关于PowerShell面向对象编程基础知识,本文就介绍这么多,希望对您有所帮助,谢谢!