如何使用"If not null Else"来设置值?

Mik*_*der 2 f#

在VB.NET中你可以写这个

Dim mammal as IAnimal = new Mammal
Dim bird as IAnimal = new Bird
' If mammal is not Nothing, animal is mammal, else it's bird
Dim animal IAnimal = If(mammal, bird) ' animal is mammal

Dim mammal as IAnimal
Dim bird as IAnimal = new Bird
' animal is now Bird
Dim animal IAnimal = If(mammal, bird)
Run Code Online (Sandbox Code Playgroud)

并在C#

IAnimal mammal = new Mammal()
IAnimal bird = new Bird()
// If mammal is not null, animal is mammal, else it's bird
IAnimal animal = mammal ?? bird; // animal is mammal

IAnimal mammal;
IAnimal bird = new Bird()
// animal is now bird
IAnimal animal = mammal ?? bird;
Run Code Online (Sandbox Code Playgroud)

但是如何在F#中做到这一点?是否有像VB.NET和C#中的短语法?

我想出了这个作为替代品,直到我发现它是否/如何完成.

let IfNotNullElse (v1, v2) = 
    if v1 <> null then
        v1
    else
        v2
Run Code Online (Sandbox Code Playgroud)

The*_*Fox 5

在惯用的自包含F#中,你不知道任何时候任何东西都可以为null,因此使用Option类型并提供默认值更为常见,如下所示:

Some 1 |> Option.defaultValue 2  // 1
None   |> Option.defaultValue 2  // 2
Run Code Online (Sandbox Code Playgroud)

但是,如果您正在使用.NET可空引用,那么您可以定义自己的空合并运算符.不幸的??是不允许作为运营商名称:

let (|?) a b = if isNull a then b else a

null |? null |? "a"  // "a"
"a" |? null  // "a"
(null:string) |? null  // null
Run Code Online (Sandbox Code Playgroud)

但请注意,这里没有懒惰的评估.|?总是评估右边的表达式.