Created
February 11, 2015 23:05
-
-
Save smoothdeveloper/350cab95490d4b729c8b to your computer and use it in GitHub Desktop.
F# simple UnionCase info reflection helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open Microsoft.FSharp.Reflection | |
module SimpleUnionCaseInfoReflection = | |
// will crash if 'T contains members which aren't only tags | |
let Construct<'T> (caseInfo: UnionCaseInfo) = FSharpValue.MakeUnion(caseInfo, [||]) :?> 'T | |
let GetUnionCaseInfoAndInstance<'T> (caseInfo: UnionCaseInfo) = (caseInfo, Construct<'T> caseInfo) | |
let AllCases<'T> = | |
FSharpType.GetUnionCases(typeof<'T>) | |
|> Seq.map GetUnionCaseInfoAndInstance<'T> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#load "SimpleUnionCaseInfoReflection.fs" | |
type Foos = Foo | Bar | Baz | |
SimpleUnionCaseInfoReflection.AllCases<Foos> |> Seq.iter (fun (caseInfo, instance) ->printfn "name: %s instance: %O is Bar? : %b" caseInfo.Name instance (instance.Equals(Foos.Bar))) | |
(* | |
> name: Foo instance: FSI_0055+Foos is Bar? : false | |
> name: Bar instance: FSI_0055+Foos is Bar? : true | |
> name: Baz instance: FSI_0055+Foos is Bar? : false | |
*) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment