I haven't had time to try to code it, but I think I can steer you in the right direction...

foo.GetType()

will be a fail; since 'foo' is a let-bound function in a module, you need to use e.g. more like

typeof<module Program>.GetMethod("foo")

assuming that the enclosing module is named 'Program' and also wishing that "typeof<module X>" were valid F# syntax. But I imagine using reflection on the assembly, and then finding type "ProgramModule", and then getting its methods, you can figure it out.

By on 6/16/2009 2:57 PM ()

Ok, finally had time to write it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
module Program

let foo (x:'t) : 't = x

/// call foo<T>(arg)
let bar (t : System.Type, arg : obj) =
    let assem = System.Reflection.Assembly.GetExecutingAssembly()
    let modul = assem.GetType("Program")
    let metho = modul.GetMethod("foo")
    let methodOfT = metho.MakeGenericMethod( [| t |] )
    methodOfT.Invoke(null, [| arg |])

let r = bar (typeof<int>, 42)
printfn "%A" r
let r2 = bar (typeof<string>, "hi")
printfn "%A" r2
By on 6/16/2009 9:12 PM ()

As per an outside discussion, for posterity, here's a more general way for any 'generic function value' (this way requires a little more boilerplate, namely FooSig):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 

let foo (x:'t) : 't = x

type FooSig = 
     abstract Invoke<'t> : 't -> 't

/// call foo<T>(arg)
let bar (t : System.Type, arg : obj) =
    let ft = { new FooSig with member __.Invoke(arg) = foo arg }
    let meth = typeof<FooSig>.GetMethod("Invoke") 
    meth.MakeGenericMethod([| t |]).Invoke(ft, [| arg |])

let r = bar (typeof<int>, 42)
printfn "%A" r
let r2 = bar (typeof<string>, "hi")
printfn "%A" r2

By on 6/17/2009 12:29 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper