Saturday, May 14, 2011

Studying F# : Generics

In Java or C#, Generics is written as <T>, T is the type parameter.

In F#, it's similar to above, we just write <'a>, 'a is the type parameter.
[<Class>]
type Reflector<'a>() =
    member r.GetMembers() =
        let ty = typeof<'a>
        ty.GetMembers()
let rflc = new Reflector<System.Math>()
// usage
Array.iter (fun it -> System.Console.WriteLine(it.ToString())) (rflc.GetMembers())
Function typeof gets the concrete type of type parameter.

This is normal generic way. And there is one more generic way - with static type parameter.
[<Class>]
type StaticReflector() =
    static member GetMembers<'a>() =
        let ty = typeof<'a>
        ty.GetMembers()
// usage
Array.iter (fun it -> System.Console.WriteLine(it.ToString())) (StaticReflector.GetMembers<System.Math>())

No comments:

Post a Comment