powershell - Powershell/.net反射-GetMethod()查找常规方法,但找不到通用方法-为什么?

标签 powershell reflection

设置:在Windows 10 / PS 5.1上,运行此程序以访问WindowsRuntime和我正在使用的WinRT类型:

Add-Type -AssemblyName System.Runtime.WindowsRuntime
[Windows.Foundation.IAsyncAction,Windows.Foundation,ContentType=WindowsRuntime]
[Windows.Foundation.IAsyncOperation`1,Windows.Foundation,ContentType=WindowsRuntime]
[Windows.Foundation.IAsyncOperationWithProgress`2,Windows.Foundation,ContentType=WindowsRuntime]

OK,现在找到我不需要的扩展方法-AsTask(),它带有一个参数,键入为[IAsyncAction]:
[System.WindowsRuntimeSystemExtensions].GetMethod('AsTask', 
                                                  [Windows.Foundation.IAsyncAction])

将有一些输出-找到一个方法。

现在尝试使用与我相同的AsTask()方法,但是这次的重载需要使用参数类型为IAsyncOperation<T>或[IAsyncOperation`1]的参数:
[System.WindowsRuntimeSystemExtensions].GetMethod('AsTask', 
                                             [Windows.Foundation.IAsyncOperation`1])

无输出。如果类型名称改为字符串,则不输出。

但是,确实存在过载。询问所有方法并随后对其进行过滤,这将找到它:
([System.WindowsRuntimeSystemExtensions].GetMethods() | 
    Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and 
               $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]

这是我正在使用的最后一段代码,它可以正常工作,导致我出现的问题是:我可以在一个调用中直接从GetMethod()请求该方法吗?

最佳答案

通用“AsTask”方法和[Windows.Foundation.IAsyncOperation`1]中的类型即使它们具有相同的GUID类型也不相同。它们在4个参数上有所不同,但它们是只读的:

Add-Type -AssemblyName System.Runtime.WindowsRuntime
$methods = [System.WindowsRuntimeSystemExtensions].GetMethods()
$taskList = $methods | ?{$_.Name -eq "AsTask"}
$asTask = $taskList | ?{$_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' }

$type1 = $asTask.GetParameters().ParameterType
$type2 = [Windows.Foundation.IAsyncOperation`1]

$attribList = ("IsGenericTypeDefinition", "IsConstructedGenericType", "GenericTypeParameters", "GenericTypeArguments")
foreach ($attrib in $attribList) {
    "$attrib : $($type1.$attrib) -> $($type2.$attrib)"
}

关于powershell - Powershell/.net反射-GetMethod()查找常规方法,但找不到通用方法-为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51229192/

相关文章:

c# - 是否在编译时优化了一些反射代码?

java - 了解 'Element'和 'TypeMirror'在 `UnmodifiableCollection`中的角色

c# - 从 C# 中检索程序集的 MVID?

powershell - TFS 构建 PowerShell 步骤中的 Robocopy 报告失败但没有错误

powershell - 有没有一种方法可以显示使用PowerShell满足条件的文本行

powershell - 测试集合是否为空

powershell - 使用 PowerShell 解锁锁定的帐户(不使用 Quest AD cmdlet)

windows - 在运行提升的 session 时加载不同的 powershell 配置文件的技术是什么

c# - 如何在运行时获取当前类名?

java - 如何使用反射获取注解类名、属性值