动态获取 Option 类型有一些困难。假设我有一个函数:
let printType x =
if (box x) = null then printfn "the type is 'null'"
else printfn "the type is %A" (x.GetType())
我们这里有输出:
printType 3 // the type is System.Int32
printType (Some(3)) // the type is Microsoft.FSharp.Core.FSharpOption`1[System.Int32]
printType None // the type is null
printType null // the type is null
获取表达式类型时如何区分 None 和 null?
在运行时,选项None
值表示为null
因此您无法确定它们的运行时类型。但是,您可以编写一个通用函数来打印选项的静态类型:
let printType (x:'T option) =
printfn "Static type is: %s" (typeof<'T>.Name)
根据您的需要,这可能会也可能不会满足您的需要。
printType (None : int option) // Int32
printType (None : string option) // String
printType None // Object (the default used by the inference)
EDIT如果您希望能够对任何参数调用该函数,您可以使用typeof<'T>
正如我的示例以及马修解决方案中的其余逻辑一样。以下代码与 Matthew 的代码片段执行相同的操作(但它不会无缘无故地创建引用):
let printType (x:'T) =
let typeOfX = typeof<'T>
if not <| FSharpType.IsUnion(typeOfX) && (box x) = null then
printfn "Static type is %s, but the value is 'null'" typeOfX.Name
else
printfn "Static type is %s and value is not 'null'" typeOfX.Name
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)