PowerShell:`New Object`-ArgumentList`与调用构造函数vs类型转换



我刚刚开始学习PowerShell的一些基础知识,无法理解New-Object和类型转换。例如:

# all of these yield the same
New-Object System.Net.Sockets.TcpListener -ArgumentList 5000
New-Object System.Net.Sockets.TcpListener(5000)
[System.Net.Sockets.TcpListener]500  # this works
# all of these yield the same
New-Object -TypeName System.Net.Sockets.TCPClient -ArgumentList "8.8.8.8", 53
New-Object System.Net.Sockets.TCPClient("8.8.8.8", 53)
[System.Net.Sockets.TCPClient]::New("8.8.8.8", 53)
# but this doesn't work
# [System.Net.Sockets.TCPClient]("8.8.8.8", 53) # does not work
  • 使用-ArgumentList和使用(arg1,...)有什么区别?类型的名称和(arg1,...)是否被解释为New-Object的两个不同参数,即使它们之间没有空格,因此(arg1,...)被指定为-ArgumentList的值
  • 为什么System.Net.Sockets.TCPClient的第二个示例的铸造不起作用?我看到的唯一区别是它接受多个参数,而System.Net.Sockets.TcpListener接受一个参数。但是,为什么PowerShell可以通过调用其构造函数将整数强制转换为System.Net.Sockets.TcpListener,而不能将数组强制转换为System.Net.Sockets.TCPClient呢?也就是说,为什么这两个不等价:
    • [System.Net.Sockets.TCPClient]::New("8.8.8.8", 53) # works
    • [System.Net.Sockets.TCPClient]("8.8.8.8", 53) # does not work

使用-ArgumentList和使用(arg1, ...)有什么区别?

  • 不要使用(arg1,...),这是方法语法,只有恰好有效-请参阅此答案的底部部分。

  • 相反,使用arg1, ...——没有括号,列表前有空格;即-ArgumentList arg1, ...(或-Args arg1, ...(的位置隐含等价物

为什么System.Net.Sockets.TCPClient的第二个示例的类型转换不起作用?

铸造只适用于两种变体:

  • 使用与单参数构造函数匹配的标量,或者在字符串的情况下,如果目标类型具有静态.Parse()方法。

  • 使用哈希表(@{ ... }(,其条目的键与目标类型的属性匹配,假设目标类型具有无参数公共构造函数。

因此,不能从值的数组中强制转换

有关详细信息,请参阅此答案。

最新更新