F#转换运算符 [英] F# Casting Operators

查看:69
本文介绍了F#转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下F#强制转换运算符有什么区别?我似乎无法理解它们为何不同以及为何如此。

What is the difference between the following F# casting operators? I can't seem to understand why and how they are all different.

(type) X
X :> type
X :?> type


推荐答案

第一个不是F#中的强制转换,但是,如果您习惯使用C#,它可能看起来像一个C#。但这实际上是在调用类型转换 function (例如 int ),并且实际上并不需要括号(并且很可能会包含所有内容)

The first isn't a cast in F#, though if you're used to C# it might appear that it works like one. But this is actually invoking a type conversion function (like int), and the parentheses aren't actually required (and are just likely to make everything more confusing).

(int) "4" // the number 4 - this is a conversion, not a cast
int "4"   // same thing, but idiomatic
int "NaN" // compiles but throws an exception at runtime
(int) (box 4) // doesn't compile because int doesn't do downcasts, just known conversions

请注意,这适用于原始类型,因为有预定义的转换函数,但不适用于任意类型:

Note that this works for primitive types, because there are predefined conversion functions, but it won't work for arbitrary types:

(bigint) 1 // no such conversion function, so this is a compile-time error

另外两个的区别是:> ; 执行向下转换(从类型到超类型,始终是安全的),而:?> 执行向下转换(从类型到子类型,这可能会il,因此中间的'?')。

The difference between the other two is that :> performs upcasts (from a type to a supertype, which is always safe) and :?> performs downcasts (from a type to a subtype, which might fail, thus the '?' in the middle).

也称为 upcast downcast 运算符,可以用类似的方式使用:

There are also named upcast and downcast operators which can be used in a similar way:

5 :> obj                 // upcast int to obj
(upcast 5 : obj)         // same
(box 5) :?> int          // downcast an obj to int (successfully)
(downcast (box 5) : int) // same
(box "5") :?> int        // downcast an obj to int (unsuccessfully)

在某些情况下,向上转换的目标类型或downcast可能已成功推断,在这种情况下,使用 upcast downcast 运算符时不需要类型批注,尽管您始终需要为:> :?> 运算符提供类型参数(尽管您需要可以提供 _ (如果您希望得到推断):

In some contexts the target type of the upcast or downcast may be successfully inferred, in which case you don't need the type annotations when using the upcast or downcast operators, while you always need to provide a type argument to the :> or :?> operators (though you can supply _ if you expect it to be inferred):

List.map (fun x -> x + 1) (downcast (box [1]))
List.map (fun x -> x + 1) (box [1] :?> _)

这篇关于F#转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆