【发布时间】:2014-01-16 13:15:27
【问题描述】:
所以我有一些 COM 类型的名称难以记住、长而笨重,所以如果可以避免的话,我宁愿在从对象投射时不必输入它们。使用Seq.cast,它将推断所需的类型并根据需要进行强制转换。
这是一个用 int 代替的简化版本:
> let o = 1 :> obj;;
val o : obj = 1
> let inc x = x+1;;
val inc : int -> int
> inc o;;
inc o;;
----^
stdin(15,5): error FS0001: This expression was expected to have type
int
but here has type
obj
好的,有道理。所以我们投了它:
> inc (o :?> int);;
val it : int = 2
但是,如果我使用 Seq.cast 进行转换,则不需要显式编写类型:
> inc ([o] |> Seq.cast |> Seq.head);;
val it : int = 2
下面有没有类似cast的函数?
> inc (o |> cast);;
val it : int = 2
是否有像 Seq.cast 这样具有类型推断功能的 F# cast 函数?
【问题讨论】:
-
您可能对
Seq.cast期望过高:像inc ([2.0] |> Seq.cast |> Seq.head)这样简单的东西会抛出InvalidCastException。
标签: casting f# type-inference