Is there any way to get a type of the null value开发者_StackOverflow? This does not work:
let a: string = null
let typ = a.GetType()
Thanks
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[]
The solution by Brian probably does what you need, but you shouldn't need it in practice.
Runtime type - If you really need to detect the type of value at runtime (using GetType
) then it is probably because the type may be more specific than what the static type suggests (i.e. it was de-serialized or created using Reflection and you got a value of type obj
or some interface). In that case, you need to handle null
explicitly, because getStaticType
will always give you obj
:
let handleAtRuntime (value:obj) =
match value with
| null -> // handle null
| _ -> let typ = value.GetType()
// do something using runtime-type information
Static type - If you just need to know the System.Type
of a statically-known type, then you should be able to write all you need using typeof<_>
. This is useful when you have generic functions:
let handleStatically (value:'T) =
let typ = typeof<'T>
// do something with the type (value still may be null)
In your example, you don't really need any dynamic behavior, because you can be sure that the type of the value is string
, so you can use Brian's solution, but using typeof<string>
would be fine too.
I'm not sure that this is the best answer, but you can use Quotations to retrieve the type with.
For example:
let get_type x = <@ x @>.Type.FullName
And test:
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[]"
精彩评论