是否可以在Powershell中将更新类型数据与泛型类型定义一起使用?
我正在实施Bart de Smet的解决方案,在这里向Powershell添加扩展方法: 它工作得很好!几乎!他过滤掉了泛型,但那是在黑暗时代(2007年),所以我试图弄清楚今天使用Powershell 3.0是否可行。下面是一个简单的例子,说明我正在尝试做什么:是否可以在Powershell中将更新类型数据与泛型类型定义一起使用?,powershell,powershell-3.0,Powershell,Powershell 3.0,我正在实施Bart de Smet的解决方案,在这里向Powershell添加扩展方法: 它工作得很好!几乎!他过滤掉了泛型,但那是在黑暗时代(2007年),所以我试图弄清楚今天使用Powershell 3.0是否可行。下面是一个简单的例子,说明我正在尝试做什么: $ls = new-object collections.generic.list[string] 'generic' update-typedata -force -typename collections.generic.li
$ls = new-object collections.generic.list[string]
'generic'
update-typedata -force -typename collections.generic.list`1 `
-membertype scriptmethod -membername test -value {'test!'}
$ls.test() # fail
'string'
update-typedata -force -typename collections.generic.list[string] `
-membertype scriptmethod -membername test -value {'test!'}
$ls.test() # works!
这将产生:
generic
Method invocation failed because [System.Collections.Generic.List`1[[System.String, mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]] doesn't contain a method
named 'test'.
At C:\Temp\blah5.ps1:12 char:1
+ $ls.test()
+ ~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
string
test!
现在,Powershell可以使用泛型类型定义。它只是没有和typedata系统集成
还是我做错了?有什么方法可以让这项工作正常进行吗?自定义类型扩展取决于
$object.PSTypeNames
-PowerShell在决定给定扩展是否应用于某个类型时,将使用您看到的任何内容
在第一个示例中,您将方法“挂接”到可能不会显示在任何对象的PSTypeName中的类型:
$ls.PSTypeNames
System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
System.Object
Update-TypeData -Force -TypeName System.Collections.Generic.List -Value {
'Works!'
} -MemberName Test -MemberType ScriptMethod
function New-GenericObject {
param (
[Parameter(Mandatory)]
$TypeName
)
$out = New-Object @PSBoundParameters
$out.PSTypeNames.Insert(
0,
($out.GetType().FullName -split '`')[0]
)
, $out
}
$ls = New-GenericObject -TypeName Collections.Generic.List[string]
$ls.Test()
显然,将任何泛型都应该使用的方法链接到System.Object是过分的(至少可以说)。您可以通过创建带有特定函数的泛型来解决此问题,该函数将包装新对象并向PSTypeNames添加一些内容:
$ls.PSTypeNames
System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
System.Object
Update-TypeData -Force -TypeName System.Collections.Generic.List -Value {
'Works!'
} -MemberName Test -MemberType ScriptMethod
function New-GenericObject {
param (
[Parameter(Mandatory)]
$TypeName
)
$out = New-Object @PSBoundParameters
$out.PSTypeNames.Insert(
0,
($out.GetType().FullName -split '`')[0]
)
, $out
}
$ls = New-GenericObject -TypeName Collections.Generic.List[string]
$ls.Test()
这更像是一个草图而不是实际的实现。。。我想真正的代理函数比简单的包装器要好得多