2011-08-25 54 views

回答

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[] 
+0

我不知道这是否是有效的F#,但它看起来足够接近我期待看到的+1 +1 lol –

+3

不错。您也可以删除输入值,而不是将其绑定到_x。 'let getStaticType(_:'T)= typeof <'T>'。 – cfern

+0

谢谢。这就是我需要的! –

1

我不知道这是最好的答案,但你可以用引文检索与类型。

例如:

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[]" 
4

布赖恩的解决方案可能做你需要什么,但你不应该需要在实践中。

运行时类型 -如果你真的需要(使用GetType),那么这可能是因为该类型可能比静态类型表明更具体的(即它是反序列检测值在运行时的类型或使用Reflection创建并获得类型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>也可以。