F#:为什么选项类型与可为空的类型不兼容? [英] F#: Why aren't option types compatible with nullable types?
问题描述
为什么"int选项"之类的选项类型与"Nullable"之类的可空类型不兼容?
Why aren't option types like "int option" compatible with nullable types like "Nullable"?
我认为造成这种差异的原因是一些语义上的原因,但我不知道那是什么.
I assume there is some semantic reason for the difference, but I can't figure what that is.
当值可能存在或不存在时,将使用F#中的选项.选项具有基础类型,并且可以包含该类型的值,也可以不具有值.
An option in F# is used when a value may or may not exist. An option has an underlying type and may either hold a value of that type or it may not have a value.
http://msdn.microsoft.com/zh-cn/library/dd233245%28VS.100%29.aspx
听起来确实像Nullable结构.
That sure sounds like the Nullable structure.
推荐答案
由于System.Nullable<'T>
的运行时表示形式选择.
Because of the runtime representation choice for System.Nullable<'T>
.
Nullable尝试用null指针表示缺少的值,并通过指向这些值的指针来显示值.
Nullable tries to represent the absent of values by the null pointer, and present values by pointers to those values.
(new System.Nullable<int>() :> obj) = null
|> printfn "%b" // true
(new System.Nullable<int>(1) :> obj).GetType().Name
|> printfn "%s" // Int32
现在考虑字符串.不幸的是,字符串是可以为空的.所以这是有效的:
Now consider strings. Unfortunately, strings are nullable. So this is valid:
null : string
但是现在null
运行时值是模棱两可的-它可以表示不存在值或null
值.因此,.NET不允许构造System.Nullable<string>
.
But now a null
runtime value is ambiguous - it can refer to either the absence of a value or a presence of a null
value. For this reason, .NET does not allow constructing a System.Nullable<string>
.
与此进行对比:
(Some (null : string) :> obj).GetType().Name
|> printfn "%s" // Option`1
话虽如此,一个人可以定义一个双射:
That being said, one can define a bijection:
let optionOfNullable (a : System.Nullable<'T>) =
if a.HasValue then
Some a.Value
else
None
let nullableOfOption = function
| None -> new System.Nullable<_>()
| Some x -> new System.Nullable<_>(x)
如果观察类型,则这些函数将'T
约束为结构,并具有零参数构造函数.因此,也许F#编译器可以通过将.c替换为Option<'T where 'T : struct and 'T : (new : unit -> 'T)>
并在必要时插入转换函数来公开.NET函数的接收/返回Nullable<'T>
.
If you observe the types, these functions constrain 'T
to be a structure and have a zero-argument constructor. So perhaps F# compiler could expose .NET functions receiving/returning Nullable<'T>
by substituting it for an Option<'T where 'T : struct and 'T : (new : unit -> 'T)>
, and inserting the conversion functions where necessary..
这篇关于F#:为什么选项类型与可为空的类型不兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!