【问题标题】:Type of the null value using F#使用 F# 的空值类型
【发布时间】:2011-08-25 08:25:10
【问题描述】:

有什么方法可以获取空值的类型吗?这不起作用:

let a: string = null
let typ = a.GetType()

谢谢

【问题讨论】:

    标签: types f# null


    【解决方案1】:
    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[]
    

    【讨论】:

    • 我不知道这是否是有效的 F#,但它看起来与我期望看到的非常接近,所以 +1 哈哈
    • 不错。您也可以删除输入值,而不是将其绑定到 _x。 let getStaticType (_:'T) = typeof&lt;'T&gt;.
    • 谢谢。这就是我需要的!
    【解决方案2】:

    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
    

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

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

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

    【讨论】:

      【解决方案3】:

      我不确定这是否是最佳答案,但您可以使用引号来检索类型。

      例如:

      let get_type x = <@ x @>.Type.FullName
      

      并测试:

      let a : string = null
      let a' = get_type a
      
      val a : string = null
      val a' : string = "System.String"
      
      let a : int[] = null
      let a' = get_type a
      
      val a : int [] = null
      val a' : string = "System.Int32[]"
      

      【讨论】:

        猜你喜欢
        • 2015-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-18
        • 2013-05-18
        • 1970-01-01
        相关资源
        最近更新 更多