ToString throws NullReferenceException for unit value ()

限于喜欢 提交于 2019-12-23 12:40:39

问题


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?


回答1:


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.




回答2:


Use the built-in string function instead of calling ToString on the object:

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


来源:https://stackoverflow.com/questions/41347374/tostring-throws-nullreferenceexception-for-unit-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!