Types 如何在F#中键入cast?
我必须枚举集合的成员,并使用成员的特定属性创建一个数组:Types 如何在F#中键入cast?,types,f#,casting,Types,F#,Casting,我必须枚举集合的成员,并使用成员的特定属性创建一个数组: let ops: int array = [| for x in app.Operations -> let op= x : IAzOperation op.OperationID |] 这里的app.Operations是iazooperation的集合,但在枚举时,将每个成员作为Obj返回。所以我想输入cas
let ops: int array = [| for x in app.Operations ->
let op= x : IAzOperation
op.OperationID |]
这里的app.Operations
是iazooperation的集合,但在枚举时,将每个成员作为Obj
返回。所以我想输入cast每个成员并访问属性。但我不知道怎么打字。
如果我按照我在这里提到的方式进行打字,它会给我以下错误:
This espression was expected to have type IAzOPeration but here has type obj.
我在这里遗漏了什么?您需要下行操作符
:?>
:
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
let ops: int array = [| for x in app.Operations do
let op = x :?> IAzOperation
yield op.OperationID |]
正如其名称中的符号?
所示,向下转换可能会失败并导致运行时异常
对于序列,您可以使用另一个选项:
let ops:int数组=
[|对于应用程序中的操作|>Seq.cast->op.OperationID |]
为确保完整性,请选择具有模式匹配的版本[|用于:?iazooperation作为op in app.Operations->op.OperationID |]
let ops: int array =
[| for op in app.Operations |> Seq.cast<IAzOperation> -> op.OperationID |]