samedi 7 juillet 2018

Powershell / .net reflection - GetMethod() finds a normal method, but not a generic one - why?

Setup: on Windows 10 / PS 5.1, run this to get access to the WindowsRuntime:

Add-Type -AssemblyName System.Runtime.WindowsRuntime
[Windows.Foundation.IAsyncAction]

NB. be sure to type the second line, and use tab completion. If I copy-paste or use the history, and don't use tab completion, the type cannot be found. After tab-completion search, it can be. If anyone can explain that, great, but that's not my main question.

OK, now find an extension method I'm not looking for - AsTask() which takes one parameter, typed as an [IAsyncAction]:

[System.WindowsRuntimeSystemExtensions].GetMethod('AsTask', 
                                                  [Windows.Foundation.IAsyncAction])

There will be some output - a method found.


Now try for the one I am looking for, the same AsTask() method, but this time the overload which takes a parameter typed IAsyncOperation<T> or [IAsyncOperation1]`:

[System.WindowsRuntimeSystemExtensions].GetMethod('AsTask', 
                                                  [Windows.Foundation.IAsyncOperation`1])

No output. No output if the type name is given as a string instead.

But that overload does exist; ask for all the methods and filter them afterwards, and this will find it:

([System.WindowsRuntimeSystemExtensions].GetMethods() | 
    Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and 
                   $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]

This last block of code is what I am using and it works, the question which led me here was: can I ask for that method directly from GetMethod() in one call?





Aucun commentaire:

Enregistrer un commentaire