简体   繁体   English

在F#中反映C#类型

[英]Reflecting C# types in F#

I've loaded a C# dll in a Fsi session. 我在Fsi会话中加载了C#dll。 Running C# methods returns some C# types. 运行C#方法会返回一些C#类型。 I've written a helper function to explore the Properties for a given C# type. 我编写了一个辅助函数来探索给定C#类型的属性。

The program is failing with an error: 程序失败并出现错误:

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

Is this possible to do? 这可能吗? Or am I beating a dead horse? 还是我在击败一匹死马?

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

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

I'm just aiming for a pretty print of C# fields. 我只是为了漂亮地打印C#字段。

Update 更新

I think I've found a way to do this. 我想我已经找到了一种方法。 And it seems to work. 而且似乎可行。 I'm not able to answer myself. 我无法回答自己。 So I'll accept the answer of anyone who gives a better example than this. 因此,我将接受给出比此更好的示例的任何人的答案。

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

As mentioned in the comments, you can use System.Reflection.PropertyInfo in the type annotation. 如注释中所述,您可以在类型注释中使用System.Reflection.PropertyInfo Your code also has typeof<s> , but s is already a variable of type System.Type , so you can just call GetProperties on s directly: 您的代码还具有typeof<s> ,但是s已经是System.Type类型的变量,因此您可以直接在s上调用GetProperties

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

getPropertyNames (typeof<System.String>)

You can also avoid the type annotation altogether by using pipe: 您还可以通过使用管道完全避免类型注释:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM