dimanche 5 novembre 2017

How to get the generic arguments of a TypeReference?

val it : TypeReference =
  System.Func`2<System.Object,TResult>
    {ContainsGenericParameter = true;
     DeclaringType = null;
     ElementType = System.Func`2;
     FullName = "System.Func`2<System.Object,TResult>";
     GenericArguments = seq [System.Object; TResult];
     GenericParameters = seq [];
     HasGenericArguments = true;
     HasGenericParameters = false;

I am trying to figure out how to get the GenericArguments of the above Mono.Cecil type and am not making any progress. Using the standard reflection API, I would just call GetGenericArguments method on the Type, but here there is nothing like that. The exists GenericParameters property, but that only works on top level TypeDefinitions whose parameters have not been been mapped to arguments. Using it on the type above would return an empty collection.

Could this be done somehow?

By the way, here is the F# script I am using to fetch the above mentioned type. My question is not at all specific for that particular type, I just needed one with generic arguments in a method parameter to illustrate my point.

#load "load-references-release.fsx"

open Mono.Cecil
open Mono.Cecil.Rocks

let mscorlib_path = @"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll"
let mscorlib = AssemblyDefinition.ReadAssembly(mscorlib_path).MainModule

let task = mscorlib.Types |> Seq.find (fun x -> x.Name = "Task`1")

let task_cons = task.GetConstructors()

let con =
    task_cons
    |> Seq.toArray
    |> fun x -> x.[8]

con.Parameters.[0].ParameterType





Aucun commentaire:

Enregistrer un commentaire