You can use the 'unbox' and 'box' operators to take advantage of type inference
inc (unbox o)
문제
So I have some COM-types with hard-to-remember, long, unwieldy names, so I'd rather not have to type them out when casting from object if I can avoid it. With Seq.cast
it'll infer the required type and cast as necessary.
Here's a simplified version with int instead:
> 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
Okay, makes sense. So we cast it:
> inc (o :?> int);;
val it : int = 2
However, if I cast it with Seq.cast I wouldn't need to explicitly write the type:
> inc ([o] |> Seq.cast |> Seq.head);;
val it : int = 2
Is there a function that works like cast
below?
> inc (o |> cast);;
val it : int = 2
Is there an F# cast
function with type inference like Seq.cast?
해결책
You can use the 'unbox' and 'box' operators to take advantage of type inference
inc (unbox o)
다른 팁
As Leaf mentioned, box
and unbox
work for conversions to/from obj
. For other types you can use the upcast
or static cast operators (:>
) for upcasting and the downcast
or dynamic cast (:?>
) operators for downcasting. A wildcard can be used in place of an explicit type, for example: x :?> _
.