How to downcast from obj to option?

前端 未结 3 1988
粉色の甜心
粉色の甜心 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:35

    To answer your last question: you can use a slight variation of Tomas' code if you need a general-purpose way to check for options without boxing values beforehand:

    let (|Option|_|) value = 
      if obj.ReferenceEquals(value, null) then None
      else
        let typ = value.GetType()
        if typ.IsGenericType && typ.GetGenericTypeDefinition() = typedefof> then
          let opt : option<_> = (box >> unbox) value
          Some opt.Value
        else None
    //val ( |Option|_| ) : 'a -> 'b option    
    
    let getValue = function
      | Option x ->  x
      | _ -> failwith "Not an option"
    
    let a1 : int = getValue (Some 42)
    let a2 : string = getValue (Some "foo")
    let a3 : string = getValue (Some 42) //InvalidCastException
    let a4 : int = getValue 42 //Failure("Not an option")
    

提交回复
热议问题