Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics ToString为单位值()抛出NullReferenceException_Generics_F#_Type Inference - Fatal编程技术网

Generics ToString为单位值()抛出NullReferenceException

Generics ToString为单位值()抛出NullReferenceException,generics,f#,type-inference,Generics,F#,Type Inference,假设我们得到了一个非常简单的函数 let fn a = a.ToString() 它的类型被推断为a->string 但是,将单位值传递给函数会导致NullReferenceException 对于上面这样的简单函数,这可能很容易解决,但实际上我处于一个更复杂的场景中: let eitherToHttp e = match e with | Either.Ok v -> OK (v.ToString()) | Either.Bad reason

假设我们得到了一个非常简单的函数

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

其类型为
or使用内置的
string
函数,而不是在对象上调用
ToString

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

您可以这样做:

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

在尝试调用
ToString

之前,这将编译为对
a
的空检查,运行时单位由
null
常量表示,因此自然不能对其调用方法。我正在移动接受的应答标签,因为另一个应答虽然不太优雅,但会生成通用函数,虽然
string
运算符似乎受到了某种限制,但有关详细信息,请参阅我的另一个SO问题:请阅读我对Mark答案的评论,了解为什么接受此答案。公平地说,您可以内联他的解决方案,这样可能会更好。你可以试试看我刚才确实试过了。似乎,使用
内联
是一种传染病。使用它会使调用
内联
函数的函数也成为
内联
,或者使其不是泛型函数。在我的问题中,请查看
eitherToHttp
函数,我希望该函数尽可能通用。内联似乎不太适合我(但也许我错了)。