PowerShell 列出类的可用构造函数
示例
在PowerShell5.0+中,可以通过调用new不带括号的静态方法来列出可用的构造函数。
PS> [DateTime]::new OverloadDefinitions ------------------- datetime new(long ticks) datetime new(long ticks,System.DateTimeKindkind) datetime new(int year, int month, int day) datetime new(int year, int month, int day, System.Globalization.Calendar calendar) datetime new(int year, int month, int day, int hour, int minute, int second) datetime new(int year, int month, int day, int hour, int minute, int second,System.DateTimeKindkind) datetime new(int year, int month, int day, int hour, int minute, int second, System.Globalization.Calendar calendar) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond,System.DateTimeKindkind) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar calendar) datetime new(int year, int month, int day, int hour, int minute, int second, int millisecond, System.Globalization.Calendar calendar,System.DateTimeKindkind)
可以使用此技术列出任何方法的重载定义
> 'abc'.CompareTo OverloadDefinitions ------------------- int CompareTo(System.Object value) int CompareTo(string strB) int IComparable.CompareTo(System.Object obj) int IComparable[string].CompareTo(string other)
对于早期版本,您可以创建自己的函数以列出可用的构造函数:
function Get-Constructor { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [type]$type ) Process { $type.GetConstructors() | Format-Table -Wrap @{ n="$($type.Name) Constructors" e={ ($_.GetParameters() | % { $_.ToString() }) -Join ", " } } } }
用法:
Get-ConstructorSystem.DateTime #Or [datetime] | Get-Constructor DateTime Constructors --------------------- Int64 ticks Int64 ticks,System.DateTimeKindkind Int32 year, Int32 month, Int32 day Int32 year, Int32 month, Int32 day, System.Globalization.Calendar calendar Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second,System.DateTimeKindkind Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, System.Globalization.Calendar calendar Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond,System.DateTimeKindkind Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, System.Globalization.Cal endar calendar Int32 year, Int32 month, Int32 day, Int32 hour, Int32 minute, Int32 second, Int32 millisecond, System.Globalization.Cal endar calendar,System.DateTimeKindkind