[英]F# Casting Operators
以下F#強制運算符之間有什么區別? 我似乎無法理解為什么以及它們如何不同。
(type) X
X :> type
X :?> type
第一個不是F#中的強制轉換,但如果你已經習慣了C#,它可能看起來像是一個。 但實際上這是調用類型轉換函數 (如int
),並且實際上並不需要括號(並且可能會使一切變得更加混亂)。
(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
請注意,這適用於基本類型,因為有預定義的轉換函數,但它不適用於任意類型:
(bigint) 1 // no such conversion function, so this is a compile-time error
其他兩個之間的區別在於:>
執行upcast(從類型到超類型,這總是安全的)和:?>
執行向下轉換(從類型到子類型,可能會失敗,因此'?'
在中間)。
還有一些名為upcast
和downcast
運算符,它們可以以類似的方式使用:
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)
在某些情況下,可以成功推斷出向上或向下轉發的目標類型,在這種情況下,在使用upcast
或downcast
運算符時不需要類型注釋,而您總是需要為:>
或提供類型參數:?>
運營商(雖然你可以提供_
如果你希望它可以推斷):
List.map (fun x -> x + 1) (downcast (box [1]))
List.map (fun x -> x + 1) (box [1] :?> _)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.