How to downcast from obj to option?

前端 未结 3 1904
粉色の甜心
粉色の甜心 2021-01-11 12:49

I have a function that takes a parameter of type object and needs to downcast it to an option.

member s.Bind(x : obj, rest) =
    let         


        
3条回答
  •  生来不讨喜
    2021-01-11 13:47

    There isn't any nice way to solve this problem currently.

    The issue is that you'd need to introduce a new generic type parameter in the pattern matching (when matching against option<'a>), but F# only allows you to define generic type parameters in function declarations. So, your only solution is to use some Reflection tricks. For example, you can define an active pattern that hides this:

    let (|SomeObj|_|) =
      let ty = typedefof>
      fun (a:obj) ->
        let aty = a.GetType()
        let v = aty.GetProperty("Value")
        if aty.IsGenericType && aty.GetGenericTypeDefinition() = ty then
          if a = null then None
          else Some(v.GetValue(a, [| |]))
        else None
    

    This will give you None or Some containing obj for any option type:

    let bind (x : obj) rest =   
        match x with    
        | SomeObj(x1) -> rest x1
        | _ -> failwith "Invalid type"
    
    bind(Some 1) (fun n -> 10 * (n :?> int))
    

提交回复
热议问题