ToString为单位值抛出NullReferenceException() [英] ToString throws NullReferenceException for unit value ()

查看:104
本文介绍了ToString为单位值抛出NullReferenceException()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$ p $ let fn a = a.ToString()

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



可能会很容易解决,但实际上我处在一个更复杂的场景中:

 让anyToHttp e = 
匹配e与
|或者.Ok v - > OK(v.ToString())
|或者.Bad原因 - > reasonToErrorCode原因

这是或者<'a,RejectReason> - > WebPart (什么 WebPart 其中实际上是无关紧要的)



e 的类型为< / code >该函数完全像在简单场景中一样抛出。



我怎样才能以很好的方式克服这个问题?
如果实际上这对所有类型都不起作用,那么应该将类型推断为泛型?

解决方案

像这样:

 让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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆