2016-02-29 44 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