使用F#的空值类型

Old*_*vec 0 null f# types

有没有办法得到一个null值的类型?这不起作用:

let a: string = null
let typ = a.GetType()
Run Code Online (Sandbox Code Playgroud)

谢谢

Bri*_*ian 5

let getStaticType<'T>(_x : 'T) = typeof<'T>
let a : string = null 
let b : int[] = null
let typ1 = getStaticType a
let typ2 = getStaticType b
printfn "%A %A" typ1 typ2
// System.String System.Int32[]
Run Code Online (Sandbox Code Playgroud)

  • 尼斯.您也可以删除输入值,而不是将其绑定到_x.`让getStaticType(_:'T)= typeof <'T>`. (3认同)

Tom*_*cek 5

Brian 的解决方案可能可以满足您的需要,但在实践中您不应该需要它。

运行时类型 -如果您确实需要在运行时检测值的类型(使用GetType),那么可能是因为该类型可能比静态类型建议的更具体(即它是反序列化的或使用反射创建的,并且您得到了类型obj或某些接口的值)。在这种情况下,您需要null显式处理,因为getStaticType总会给您obj

let handleAtRuntime (value:obj) =
  match value with 
  | null -> // handle null
  | _ -> let typ = value.GetType()
         // do something using runtime-type information
Run Code Online (Sandbox Code Playgroud)

静态类型 -如果您只需要知道System.Type静态已知类型的 ,那么您应该能够使用 编写所需的所有内容typeof<_>。当您具有通用函数时,这很有用:

let handleStatically (value:'T) =
  let typ = typeof<'T>
  // do something with the type (value still may be null)
Run Code Online (Sandbox Code Playgroud)

在您的示例中,您实际上并不需要任何动态行为,因为您可以确定值的类型是string,因此您可以使用 Brian 的解决方案,但使用typeof<string>也可以。