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

Kap*_*pil 21 f# types casting

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

  let ops: int array = [| for x in app.Operations ->
                            let op=  x : IAzOperation
                            op.OperationID |] 
Run Code Online (Sandbox Code Playgroud)

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

This espression was expected to have type IAzOPeration but here has type obj.
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

pad*_*pad 24

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

let ops: int array = [| for x in app.Operations do
                          let op =  x :?> IAzOperation
                          yield op.OperationID |] 
Run Code Online (Sandbox Code Playgroud)

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

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

let ops: int array = 
    [| for op in app.Operations |> Seq.cast<IAzOperation> -> op.OperationID |] 
Run Code Online (Sandbox Code Playgroud)

  • 为了完整起见,使用模式匹配的版本 [| 为了 :?IAzOperation 作为 app.Operations 中的 op -&gt; op.OperationID |] (2认同)

Sma*_*EGA 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
Run Code Online (Sandbox Code Playgroud)