【发布时间】:2011-08-25 08:25:10
【问题描述】:
有什么方法可以获取空值的类型吗?这不起作用:
let a: string = null
let typ = a.GetType()
谢谢
【问题讨论】:
有什么方法可以获取空值的类型吗?这不起作用:
let a: string = null
let typ = a.GetType()
谢谢
【问题讨论】:
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[]
【讨论】:
let getStaticType (_:'T) = typeof<'T>.
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<_> 编写您需要的所有内容。当您有通用函数时,这很有用:
let handleStatically (value:'T) =
let typ = typeof<'T>
// do something with the type (value still may be null)
在您的示例中,您实际上并不需要任何动态行为,因为您可以确定值的类型是 string,因此您可以使用 Brian 的解决方案,但使用 typeof<string> 也可以。
【讨论】:
我不确定这是否是最佳答案,但您可以使用引号来检索类型。
例如:
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[]"
【讨论】: