如何在F#中输入强制转换?

时间:2012-03-27 13:17:23

标签: types f# casting

我必须枚举集合的成员并创建一个具有成员特定属性的数组:

  let ops: int array = [| for x in app.Operations ->
                            let op=  x : IAzOperation
                            op.OperationID |] 

此处app.Operations是IAzOperation的集合,但在枚举时,将每个成员返回为Obj。所以我想输入每个成员并访问该属性。但不确定如何进行类型转换。 如果我按照我在这里提到的方式进行类型转换,它会给我错误:

This espression was expected to have type IAzOPeration but here has type obj.

我在这里缺少什么?

2 个答案:

答案 0 :(得分:24)

您需要向下转型运算符:?>

let ops: int array = [| for x in app.Operations do
                          let op =  x :?> IAzOperation
                          yield op.OperationID |] 

如其名称中的符号?表示,向下转换可能会失败并导致运行时异常。

如果是序列,您还可以选择使用Seq.cast

let ops: int array = 
    [| for op in app.Operations |> Seq.cast<IAzOperation> -> op.OperationID |] 

答案 1 :(得分:10)

type Base1() =
    abstract member F : unit -> unit
    default u.F() =
     printfn "F Base1"

type Derived1() =
    inherit Base1()
    override u.F() =
      printfn "F Derived1"


let d1 : Derived1 = Derived1()

// Upcast to Base1.
let base1 = d1 :> Base1

// This might throw an exception, unless
// you are sure that base1 is really a Derived1 object, as
// is the case here.
let derived1 = base1 :?> Derived1

// If you cannot be sure that b1 is a Derived1 object,
// use a type test, as follows:
let downcastBase1 (b1 : Base1) =
   match b1 with
   | :? Derived1 as derived1 -> derived1.F()
   | _ -> ()

downcastBase1 base1