f# - 当存在另一个具有相同名称的类型时反射(reflect)在 F# 模块上

标签 f#

我正在尝试获取 MethodInfo对于模块中的函数:PersistentVector.ofSeq .我遇到的问题是有一个通用类型定义为与模块同名:PersistentVector<'a> .

我想这样做:

let methodInfo = typedefof<PersistentVector>.GetMethod("ofSeq")
let finalMethod = methodInfo.MakeGenericMethod(itemType)
finalMethod.Invoke(...)

但是编译失败(第 1 行)并出现错误:The type 'FSharpx.Collections.PersistentVector<_>' expects 1 type argument(s) but 0 given.

如果我将第 2 行更改为:

let methodInfo = typedefof<PersistentVector<_>>.GetMethod("ofSeq")

编译但在运行时返回 null,因为正在检索的类型是通用的 PersistentVector 类型,它没有“ofSeq”方法。

我可以让事情像这样工作:

let pvModuleTypeFullName = "FSharpx.Collections.PersistentVectorModule"
let pvModuleType = Assembly.GetAssembly(typedefof<PersistentVector<_>>).GetType(pvModuleTypeFullName)
let methodInfo = pvModuleType.GetMethod("ofSeq")
let finalMethod = methodInfo.MakeGenericMethod(itemType)
finalMethod.Invoke(...)

但这似乎很老套,我想知道是否有更好的方法。

最佳答案

是的,很遗憾 typeof<_>不能将模块作为参数,只能将类型作为参数(尽管在 .NET 表示中模块类型)。这是另一种方法:

open Quotations.Patterns
let finalMethod = 
    let (Lambda(_,Call(None,m,[_]))) = <@ PersistentVector.ofSeq @>
    m.GetGenericMethodDefinition().MakeGenericMethod(itemType)
...

关于f# - 当存在另一个具有相同名称的类型时反射(reflect)在 F# 模块上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34096114/

相关文章:

f# - 使用 Websharper 的静态页面?

asp.net-mvc-3 - 我应该在 MVC3 和 ASP.net 中尝试 F# 吗?

在 F# 中与类型参数进行转换

F# 类型推断和通用函数参数

.net - 从 F# 中的 lambda 表达式内部产生

io - 使用 F# 读取 MNIST 数据集

f# - 将大量函数组合在一起时堆栈溢出

f# - 如何使用无法在 F# 中控制其类型定义的操作数来定义重载运算符?

functional-programming - 在 F# 中模拟多态变体?

rest - Suave with f# - 如何在 f# 聊天应用程序中使用 rest api 和 websocket 端口?