2012-03-27 19 views
20

devo enumerare i membri di un insieme e creare una matrice con una particolare struttura dei componenti:Come digitare il cast in F #?

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

Qui app.Operations è una raccolta di IAzOperation ma censimento, restituisce ogni membro come Obj. Quindi voglio digitare cast ogni membro e accedere alla proprietà. ma non sono sicuro di come convertirlo. Se typecast il modo in cui ho parlato qui, mi dà errore:

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

Che cosa mi manca qui?

risposta

23

È necessario l'operatore downcasting :?>:

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

come simbolo ? nel suo nome indica, downcasting potrebbe fallire e portare a un'eccezione di runtime.

In caso di sequenze, hai un'altra possibilità di utilizzare Seq.cast:

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

Per completezza, la versione con il pattern matching [| per:? IAzOperation as op in app.Operations -> op.OperationID |] – desco

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 
Problemi correlati