Jac*_*eja 13 powershell powershell-3.0
例如,我有一个.NET对象,$m具有以下方法重载:
PS C:\Users\Me> $m.GetBody
OverloadDefinitions
-------------------
T GetBody[T]()
T GetBody[T](System.Runtime.Serialization.XmlObjectSerializer serializer)
Run Code Online (Sandbox Code Playgroud)
如果我尝试调用无参数方法,我得到:
PS C:\Users\Me> $m.GetBody()
Cannot find an overload for "GetBody" and the argument count: "0".
At line:1 char:1
+ $m.GetBody()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Run Code Online (Sandbox Code Playgroud)
据我所知,PowerShell v3.0应该可以更容易地使用泛型.显然我需要告诉它我想要什么类型返回,但我无法弄清楚语法.
Cha*_*sch 13
看起来您正在尝试调用泛型方法.
在powershell中,这可以通过以下方式完成:
$nonGenericClass = New-Object NonGenericClass
$method = [NonGenericClass].GetMethod("SimpleGenericMethod")
$gMethod = $method.MakeGenericMethod([string])
# replace [string] with the type you want to use for T.
$gMethod.Invoke($nonGenericClass, "Welcome!")
Run Code Online (Sandbox Code Playgroud)
有关更多信息和其他示例,请参阅此精彩博客文章.
对于您的示例,您可以尝试:
$Source = @"
public class TestClass
{
public T Test<T>()
{
return default(T);
}
public int X;
}
"@
Add-Type -TypeDefinition $Source -Language CSharp
$obj = New-Object TestClass
$Type = $obj.GetType();
$m = $Type.GetMethod("Test")
$g = new-object system.Guid
$gType = $g.GetType()
$gm = $m.MakeGenericMethod($gType)
$out = $gm.Invoke( $obj, $null)
#$out will be the default GUID (all zeros)
Run Code Online (Sandbox Code Playgroud)
这可以通过以下方式简化:
$Type.GetMethod("Test").MakeGenericMethod($gType).Invoke( $obj, $null)
Run Code Online (Sandbox Code Playgroud)
这已经在powershell 2和powershell 3中进行了测试.
如果您有一个更详细的示例,了解您如何遇到这种通用方法,我将能够提供更多详细信息.我还没有看到任何微软cmdlet返回任何给你通用方法的东西.唯一出现的时间是使用c#或vb.net中的自定义对象或方法.
要在没有任何参数的情况下使用它,您可以仅使用第一个参数调用Invoke.$ gMethod.Invoke($ nonGenericClass)
在对象实例上调用通用方法:
$instance.GetType().GetMethod('MethodName').MakeGenericMethod([TargetType]).Invoke($instance, $parameters)
Run Code Online (Sandbox Code Playgroud)
调用静态泛型方法(另请参阅在 PowerShell 中调用泛型静态方法):
[ClassType].GetMethod('MethodName').MakeGenericMethod([TargetType]).Invoke($null, $parameters)
Run Code Online (Sandbox Code Playgroud)
请注意,AmbiguousMatchException当还有该方法的非泛型版本时,您将遇到一个问题(请参阅如何在 .NET 中使用 GetMethod 区分泛型和非泛型签名?)。GetMethods()然后使用:
([ClassType].GetMethods() | where {$_.Name -eq "MethodName" -and $_.IsGenericMethod})[0].MakeGenericMethod([TargetType]).Invoke($null, $parameters)
Run Code Online (Sandbox Code Playgroud)
(请注意,可能有不止一种方法与上述过滤器匹配,因此请务必对其进行调整以找到您需要的方法。)
提示:您可以像这样编写复杂的泛型类型文字(请参阅Powershell 中泛型类型的泛型类型):
[System.Collections.Generic.Dictionary[int,string[]]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6663 次 |
| 最近记录: |