What is the simplest way to access data of an F# discriminated union type in C#?

前端 未结 7 1223
耶瑟儿~
耶瑟儿~ 2020-12-10 01:23

I\'m trying to understand how well C# and F# can play together. I\'ve taken some code from the F# for Fun & Profit blog which performs basic validation returning a discr

7条回答
  •  庸人自扰
    2020-12-10 01:52

    I'm using the next methods to interop unions from F# library to C# host. This may add some execution time due to reflection usage and need to be checked, probably by unit tests, for handling right generic types for each union case.

    1. On F# side
    type Command = 
         | First of FirstCommand
         | Second of SecondCommand * int
    
    module Extentions =
        let private getFromUnionObj value =
            match value.GetType() with 
            | x when FSharpType.IsUnion x -> 
                let (_, objects) = FSharpValue.GetUnionFields(value, x)
                objects                        
            | _ -> failwithf "Can't parse union"
    
        let getFromUnion<'r> value =    
            let x = value |> getFromUnionObj
            (x.[0] :?> 'r)
    
        let getFromUnion2<'r1,'r2> value =    
            let x = value |> getFromUnionObj
            (x.[0] :?> 'r1, x.[1] :? 'r2)
    
    1. On C# side
            public static void Handle(Command command)
            {
                switch (command)
                {
                    case var c when c.IsFirstCommand:
                        var data = Extentions.getFromUnion(change);
                        // Handler for case
                        break;
                    case var c when c.IsSecondCommand:
                        var data2 = Extentions.getFromUnion2(change);
                        // Handler for case
                        break;
                }
            }
    

提交回复
热议问题