29 people like it.

Convert a obj list to a typed list without generics

This is used for building things with reflection at runtime. As ConstructorInfo arguments require typed collections, it is necessary when parsing to reflected records to first build up contents and then afterward convert the collected obj[] to a 'a[]. This is finally cast back to obj so it can be used as a ConstructorInfo argument.

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
type ReflectiveListBuilder = 
    static member BuildList<'a> (args: obj list) = 
        [ for a in args do yield a :?> 'a ] 
    static member BuildTypedList lType (args: obj list) = 
        typeof<ReflectiveListBuilder>
            .GetMethod("BuildList")
            .MakeGenericMethod([|lType|])
            .Invoke(null, [|args|])
static member ReflectiveListBuilder.BuildList : args:obj list -> 'a list

Full name: Script.ReflectiveListBuilder.BuildList
val args : obj list
type obj = System.Object

Full name: Microsoft.FSharp.Core.obj
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val a : obj
static member ReflectiveListBuilder.BuildTypedList : lType:System.Type -> args:obj list -> obj

Full name: Script.ReflectiveListBuilder.BuildTypedList
val lType : System.Type
val typeof<'T> : System.Type

Full name: Microsoft.FSharp.Core.Operators.typeof
type ReflectiveListBuilder =
  static member BuildList : args:obj list -> 'a list
  static member BuildTypedList : lType:Type -> args:obj list -> obj

Full name: Script.ReflectiveListBuilder
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/1L
Posted:11 years ago
Author:Rick Minerich
Tags: reflection , collections