如何在fsx文件中执行模块的typeof? [英] How to do typeof of a module in a fsx file?

查看:72
本文介绍了如何在fsx文件中执行模块的typeof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含以下代码的Foo.fsx脚本:

Let's say I have a Foo.fsx script that contains this code:

module Bar =
  let foobar = "foo"+"bar"

open Bar
let a = System.Reflection.Assembly.GetExecutingAssembly()
let ty = a.GetType("Foo.Bar") // but it returns null here

我该如何实现?谢谢!

推荐答案

这是一个棘手的问题,因为F#交互式将所有类型编译为带有某些错误名称的类型(并且执行程序集可以包含同一类型的多个版本).

This is a tricky question, because F# interactive compiles all types into types with some mangled names (and the executing assembly can contain multiple versions of the same type).

我设法用一个简单的技巧来做到这一点-您将一个附加类型添加到模块中-然后您可以使用typeof<..>来获取有关此类型的信息.模块内部的类型被编译为嵌套类型,因此您可以从此(嵌套)类型获取表示模块的类型的名称:

I managed to do it using a simple trick - you'd add an additional type to the module - then you can use typeof<..> to get information about this type. The type inside a module is compiled as a nested type, so you can get the name of the type representing the module from this (nested) type:

module Bar = 
  let foobar = "foo"+"bar" 
  type A = A

// Get type of 'Bar.A', the name will be something like "FSI_0001+Bar+A",
// so we remove the "+A" from the name and get "FSI_0001+Bar"
let aty = typeof<Bar.A>
let barName = aty.FullName.Substring(0, aty.FullName.Length - "+A".Length)
let barTy = aty.Assembly.GetType(barName)

// Get value of the 'foobar' property - this works!
barTy.GetProperty("foobar").GetValue(null, [| |])

您可能可以简单地在程序集中搜索所有类型以查找+Bar.那也行得通.上面技巧的好处是您可以引用该类型的特定版本(如果多次交互运行该代码,则将获得与当前Bar.A类型相对应的模块的引用)

You could probably simply search all types in the assembly looking for +Bar. That would work as well. The benefit of the trick above is that you get a reference to the specific version of the type (if you interactively run the code multiple times, you'll get a reference to the module corresponding to the current Bar.A type)

作为一个附带说明,在将来的F#版本中有一些关于支持moduleof<Bar>(或类似内容)的讨论-这有点不雅致,因为它不是像typeof那样的真实函数/值,但是这将非常有用!

As a side-note, there were some discussions about supporting moduleof<Bar> (or something like that) in future versions of F# - this is a bit inelegant as it is not a real function/value like typeof, but it would very useful!

这篇关于如何在fsx文件中执行模块的typeof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆