2016-02-29 46 views
1

我已經在Fsi會話中加載了C#dll。運行C#方法會返回一些C#類型。我寫了一個幫助函數來探索給定C#類型的屬性。在F#中反映C#類型

該方案是一個錯誤失敗:

stdin(95,21): error FS0039: The type 'RuntimePropertyInfo' is not defined 

這是可能的嗎?還是我打死馬?

let getPropertyNames (s : System.Type)= 
    Seq.map (fun (t:System.Reflection.RuntimePropertyInfo) -> t.Name) (typeof<s>.GetProperties()) 

typeof<TypeName>.GetProperties() //seems to work.

我只是瞄準了C#字段的漂亮打印。

更新

我想我已經找到了一種方法來做到這一點。它似乎工作。我無法回答自己。所以我會接受任何比這更好的例子的答案。

let getPropertyNames (s : System.Type)= 
    let properties = s.GetProperties() 
    properties 
     |> Array.map (fun x -> x.Name) 
     |> Array.iter (fun x -> printfn "%s" x) 
+2

'System.Reflection.RuntimePropertyInfo'似乎是內部的,並且在.NET 4.0中被封裝。是否有你試圖使用它而不是'System.Reflection.PropertyInfo'的原因?我從來沒有用過前者,但也許你已經嘗試過後者,並有一個原因,你沒有使用它 - 這就是爲什麼我想知道。 – Roujo

+0

@Roujo我在屬性本身做了一個typeof。這是我得到的類型。我應該可能檢查了我自己。無論如何,我認爲我找到了一種可以在沒有太多類型註釋的情況下完成這項工作的方法。 – 6D65

回答

2

正如評論中所述,您可以在類型註釋中使用System.Reflection.PropertyInfo。您的代碼也有typeof<s>,但s已經System.Type類型的變量,所以你可以叫GetPropertiess直接:

let getPropertyNames (s : System.Type)= 
    Seq.map (fun (t:System.Reflection.PropertyInfo) -> t.Name) (s.GetProperties()) 

getPropertyNames (typeof<System.String>) 

您還可以避免類型標註完全用管:

let getPropertyNames (s : System.Type)= 
    s.GetProperties() |> Seq.map (fun t -> t.Name) 
+0

這會做。看上去不錯。謝謝。 – 6D65