How do you get a discriminatory union type from a Case instance?

Given these two discriminatory unions, I would like to get DeclaringType from the instance instance.

 type SingleCaseUnion = | One type MultiCaseUnion = | Two | Three 

An example for each case will be as follows:

 getDiscriminatedUnionType One = typeof<SingleCaseUnion> // true getDiscriminatedUnionType Three = typeof<MultiCaseUnion> // true 

My first attempt was to get the case type and get its base class, this works because in F # a subtype is created for each case.

 MultiCaseUnion.Two.GetType().BaseType = typeof<MultiCaseUnion> // true 

However, for one case of union, this does not work because nested types are not created.

 SingleCaseUnion.One.GetType().BaseType = typeof<SingleCaseUnion> // false 

My second attempt to get a more reliable solution was to use the FSharp Reflection helpers.

 FSharpType.GetUnionCases(unionValue.GetType()).First().DeclaringType 

This works for all cases, but it should generate UnionCaseInfo instances for each case, which seems somewhat unnecessary.

Is there something I could miss? Sort of:

 FSharpValue.GetUnionFromCase(SingleCaseUnion.One) 
+6
source share
1 answer

What about

 open FSharp.Reflection type FSharpType = static member GetUnionType t = let ownType = t.GetType() assert FSharpType.IsUnion(ownType) let baseType = ownType.BaseType if baseType = typeof<System.Object> then ownType else baseType 

Test:

 (FSharpType.GetUnionType MultiCaseUnion.Three).Name //MultiCaseUnion (FSharpType.GetUnionType SingleCaseUnion.One).Name //SingleCaseUnion 
+4
source

Source: https://habr.com/ru/post/1013372/


All Articles