Powershell-类的方法中的可选参数

Powershell-类的方法中的可选参数,powershell,Powershell,在powershell函数中,我可以使用 Function myFunction { Param( [Parameter(Mandatory=$True)][string]$foo, [Parameter(Mandatory=$False)][string]$bar = "whatever" ) .... } 但这似乎仅限于函数——方法是否也有类似之处 class MyClass { ... [void]MethodA { Par

在powershell函数中,我可以使用

Function myFunction {
    Param(
        [Parameter(Mandatory=$True)][string]$foo,
        [Parameter(Mandatory=$False)][string]$bar = "whatever"
    )
....
}
但这似乎仅限于函数——方法是否也有类似之处

class MyClass {
...
    [void]MethodA {
    Param(
    ....
不要为我工作。

解释器抱怨类方法参数列表中缺少“(”。

向类添加方法的工作方式与大多数其他脚本语言中的工作方式相同。您可能希望添加一个块,而不是
[void]MethodA{Param()…}
,如中所述:

正如你的标题所说的可选参数(但你的问题没有)一个简短的词

通常,对于这种情况,您需要多个签名。这意味着您创建了一个方法
MethodA($arg1,$arg2)
和一个委托方法,如
MethodA($arg1){MethodA($arg1,$null)}

class MyClass {
    #...
    [void]MethodA ($param) {
        #...
    }
}