2011-08-25 55 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>也可以。