ToString 为单位值抛出 NullReferenceException ()

ToString throws NullReferenceException for unit value ()

假设我们有一个非常简单的函数

let fn a = a.ToString()

它的类型被推断为 a -> string 但是,将单位值传递给函数会导致 NullReferenceException。

对于像上面这样的简单函数,这可能很容易解决,但实际上我处于更复杂的场景中:

let eitherToHttp e = 
    match e with
    | Either.Ok v ->        OK (v.ToString()) 
    | Either.Bad reason ->  reasonToErrorCode reason

这个的类型是Either<'a, RejectReason> -> WebPartWebPartEither实际上是什么在这里无关紧要)

e 的类型为 Either<unit, RejectReason> 的情况下,函数的抛出与简单情况下完全相同。

我怎样才能很好地克服这个问题? 如果实际上这不适用于所有类型,是否应该将类型推断为通用类型?

使用内置的 string 函数而不是对对象调用 ToString

> string 42;;
val it : string = "42"
> string ();;
val it : string = ""

你可以这样做:

let fn a = match box a with
           | null -> ""
           | _ -> a.ToString()

在尝试调用 ToString.

之前,这会编译为对 a 进行空检查