我一直在使用哈希表从函数返回复杂的数据,并且效果很好,但是我想对键进行强类型化,因为我在其中有布尔值,字符串,字符串数组,有序字典等。返回的哈希表。所以,给定这样的东西
[hashtable]$hashtable = @{
one = 1
two = "two"
}
我遇到的问题是每个键的类型都是弱类型。我想基本上做到这一点
[hashtable]$hashtable = @{
[int]one = 1
[string]two = "two"
}
但这不是有效的代码。所以我想我可以做到
[psCustomObject]$object = [psCustomObject]@{
[int]one = 1
[string]two = "two"
}
但这也是无效的。我觉得这有点丑陋,而且也不起作用
$object = New-Object -typeName:PSObject
$object | Add-Member -memberType:int -name:'one' -value:1
$object | Add-Member -memberType:string -name:'two' -value:'two'
那么,我是SOL,没有办法,也没有优雅的办法来创建具有强类型属性的自定义对象吗?
答案 0 :(得分:0)
您需要在哈希表文字中键入值表达式:
PS C:\> $object = [PSCustomObject]@{
one = [int]1
two = [string]"two"
}
PS C:\> $object|gm -MemberType NoteProperty
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
one NoteProperty int one=1
two NoteProperty string two=two
但是,这不会阻止任何人在任何属性中存储非整数或非字符串-psobject属性根本不是强类型。
如果要为属性输入类型安全性,则需要创建new type with the class
keyword:
class MyOneTwo
{
[int]$One
[string]$Two
MyOneTwo(){}
MyOneTwo([int]$one, [string]$two){
$this.One = $one
$this.Two = $two
}
}
# Create instances with ::new(), New-Object or a cast:
$object = [MyOneTwo]::new(1,"2")
$object = New-Object MyOneTwo -Property @{ One = 1; Two = "2" }
$object = [MyOneTwo]@{ One = 1; Two = "2" }