在 F# 中使用可空引用类型
Using Nullable Reference Types in F#
在 F# 中,如果您要与另一种 .NET 语言进行互操作,或者如果您使用 AllowNullLiteral
属性,则引用类型可以是 null
。马上想到的例子是字符串:
let str: string = null
但是对于 C# 8 和 dotnet core 3,我们可以选择 Nullable Reference Types。我将不得不用 C# 编写上面的代码,如:
string? str = null;
有没有办法在 F# 中也选择加入可空引用类型,这样用其他语言定义的类型就不能是 null
,如果可以的话,将它们写成可空引用,例如:
let str: string = null // error cannot do this
let str: string? = null
我知道我们可以使用选项转换可能预期为 null
的类型:
let str : string = null
let strOpt = Option.ofObj str
我的问题是:是否存在使不可能创建引用类型null
,如string
,而不明确声明它是在 F# 中可为空?
来自https://www.infoq.com/news/2019/04/FSharp-Nulls/,
"F# currently supports several versions of nullability. First there are normal .NET
reference types. Today there is no way to unequivocally inform the compiler if a
specific reference type variable is nullable or not, so their use in F# is discouraged."
"The preferred alternative is Option. Also known as a “maybe” type, this is a type-
safe way to express the concept of nullability. When used with idiomatic F# code, you
can only read the value after checking to see if it is non-null (not “none” in F#
parlance). This is usually done via pattern matching."
但是,是否希望有一种干净的方式与这些互操作? annotations 得到了 F# 团队的认可,并且可以找到可空引用类型的提案 here。截至今天,该提案已“原则上批准”,但还没有原型实施。
在 F# 中,如果您要与另一种 .NET 语言进行互操作,或者如果您使用 AllowNullLiteral
属性,则引用类型可以是 null
。马上想到的例子是字符串:
let str: string = null
但是对于 C# 8 和 dotnet core 3,我们可以选择 Nullable Reference Types。我将不得不用 C# 编写上面的代码,如:
string? str = null;
有没有办法在 F# 中也选择加入可空引用类型,这样用其他语言定义的类型就不能是 null
,如果可以的话,将它们写成可空引用,例如:
let str: string = null // error cannot do this
let str: string? = null
我知道我们可以使用选项转换可能预期为 null
的类型:
let str : string = null
let strOpt = Option.ofObj str
我的问题是:是否存在使不可能创建引用类型null
,如string
,而不明确声明它是在 F# 中可为空?
来自https://www.infoq.com/news/2019/04/FSharp-Nulls/,
"F# currently supports several versions of nullability. First there are normal .NET reference types. Today there is no way to unequivocally inform the compiler if a specific reference type variable is nullable or not, so their use in F# is discouraged."
"The preferred alternative is Option. Also known as a “maybe” type, this is a type- safe way to express the concept of nullability. When used with idiomatic F# code, you can only read the value after checking to see if it is non-null (not “none” in F# parlance). This is usually done via pattern matching."
但是,是否希望有一种干净的方式与这些互操作? annotations 得到了 F# 团队的认可,并且可以找到可空引用类型的提案 here。截至今天,该提案已“原则上批准”,但还没有原型实施。