gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:53:44 25 4
gpt4 key购买 nike

设置:在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com