ToString为单位值抛出NullReferenceException() [英] ToString throws NullReferenceException for unit value ()
问题描述
$ p $
let fn a = a.ToString()
它的类型被推断为 a - >字符串
但是,将单位值传递给该函数会导致NullReferenceException异常。
可能会很容易解决,但实际上我处在一个更复杂的场景中:
让anyToHttp e =
匹配e与
|或者.Ok v - > OK(v.ToString())
|或者.Bad原因 - > reasonToErrorCode原因
这是或者<'a,RejectReason> - > WebPart
(什么 WebPart
和其中
实际上是无关紧要的)
在 e
的类型为或
我怎样才能以很好的方式克服这个问题?
如果实际上这对所有类型都不起作用,那么应该将类型推断为泛型?
像这样:
让fn a =将盒子a与
匹配| null - >
| _ - > a.ToString()
这只是对 a进行空检查在尝试调用
ToString
之前
Say we got a very simple function
let fn a = a.ToString()
It's type gets inferred as a -> string
However, passing a unit value to the function results in a NullReferenceException.
In case of simple functions like above, this might be worked around easily, but I'm actually in a more complex scenario:
let eitherToHttp e =
match e with
| Either.Ok v -> OK (v.ToString())
| Either.Bad reason -> reasonToErrorCode reason
The type of this is Either<'a, RejectReason> -> WebPart
(what WebPart
and Either
actually are is irrelevant here)
In a scenario where the type of e
is Either<unit, RejectReason>
the function throws exactly like in the simple scenario.
How can I overcome this in a nice way? Should the types be inferred as generic if in fact this does not work for ALL types?
You can do something like this:
let fn a = match box a with
| null -> ""
| _ -> a.ToString()
This compiles down to just a null check on a
before attempting to call ToString
.
这篇关于ToString为单位值抛出NullReferenceException()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!