如何宣布可以为空的歧视联盟?

时间:2017-07-12 18:37:10

标签: f#

我有像这样的歧视联盟

type foo =
| Yes of bool
| Number of decimal

我有另一种类型,我试图将此DS视为可以为空的成员

type test(value) =
member this.Value : Nullable<foo> = value

当我尝试这样做时,我会得到&#34;一个通用的构造要求类型&#34; foo&#34;有一个公共默认构造函数。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

.NET的Nullable<T>类型实际上设计用于int等值类型,而不是string等引用类型,因为它们已经可以为空。< / p>

默认情况下,受歧视的联合是引用类型,因为它们实际上已编译为类。但它们可能被迫成为一个结构,这将使它成为一种价值类型。但是,当您这样做时,会出现另一个错误:If a union type has more than one case and is a struct, then all fields within the union type must be given unique names。您可以在每个案例中命名值,如下例所示:

[<Struct>]
type foo =
| Yes of yes:bool
| Number of number:decimal

现在你可以拥有Nullable<foo>。但你可能实际上并不想这样做。 F#中用于表示&#34; nullable&#34;的正常方式参考值和值类型的值是使用Option类型。因此,您应该将类​​型更改为foo,而不是使Option<foo>成为结构:

type test(value) =
    member this.Value : Option<foo> = value

test(Some (Number 1M)) // some value
test(None) // no value

F#很大程度上使得F#中定义的类型无法为空,因此您可以将Option用于所有内容,而不是区分引用和值类型。 Nullable仅对使用现有.NET代码非常有用。