如何为[System.String[]]类型添加自定义ToSentence方法?
解决方案
方法1:添加实例ScriptMethod(直接用脚本块)
如果接受实例方法,直接用Update-TypeData注册ScriptMethod即可,这是PowerShell中用脚本扩展类型的常规方式:
Update-TypeData -TypeName System.String[] -MemberName ToSentence -MemberType ScriptMethod -Value { switch ($this.Count) { 0 { '' } 1 { "$($this[0])." } 2 { "$($this[0]) and $($this[1])." } default { "$($this[0..($this.Count-2)] -join ', ') and $($this[-1])." } } }
测试调用:
@('apple', 'pear', 'orange') | ForEach-Object { $_.ToSentence() } # 输出:apple, pear and orange.
方法2:添加静态ScriptMethod(优先选项)
如果要实现静态方法,指定-MemberType StaticScriptMethod,调用时通过类型名触发:
Update-TypeData -TypeName System.String[] -MemberName ToSentence -MemberType StaticScriptMethod -Value { param([string[]]$InputArray) switch ($InputArray.Count) { 0 { '' } 1 { "$($InputArray[0])." } 2 { "$($InputArray[0]) and $($InputArray[1])." } default { "$($InputArray[0..($InputArray.Count-2)] -join ', ') and $($InputArray[-1])." } } }
测试调用:
[System.String[]]::ToSentence(@('apple', 'pear', 'orange')) # 输出:apple, pear and orange.
原命令出错原因
你使用了-MemberType CodeMethod,但这个类型要求传入**.NET MethodInfo对象**(比如通过反射获取的已存在方法),而非PowerShell脚本块。脚本块对应的正确成员类型是ScriptMethod或StaticScriptMethod。
补充说明
上述代码通过switch分支覆盖了空数组、单元素、双元素的场景,比原脚本更健壮:
- 空数组返回空字符串
- 单元素直接追加句号(如
@('banana')输出banana.) - 双元素使用
x and y.格式,避免多余逗号
内容的提问来源于stack exchange,提问作者jeremywat
相关产品推荐
相关产品推荐

