我已经为这个问题苦苦挣扎了很长一段时间,似乎找不到任何解决方案。让我为您简化一下。
我有一个想要调用的通用函数,但我只想将其类型参数作为实例来调用。例子
let foo_a<'a> () = typeof<'a>
let foo_b (t : System.Type) = foo_a<t>() // of course this does not work
Run Code Online (Sandbox Code Playgroud)
我希望以下陈述属实
foo_a<int>() = foo_b(typeof<int>)
Run Code Online (Sandbox Code Playgroud)
在 C# 中,我会反映 foo_a 的 MethodInfo 并执行 MakeGenericMethod(t),但在 F# 中如何执行此操作?
只是为了澄清,翻转依赖关系并让 foo_a 调用 foo_b 来代替,对我来说不是一个选择。
正如 @svick 所说,在 F# 中没有特殊的方法可以做到这一点——您需要像在 C# 中一样使用反射。
下面是一个可以粘贴到 F# 交互式中的简单示例:
open System.Reflection
type Blah =
//
static member Foo<'T> () =
let argType = typeof<'T>
printfn "You called Foo with the type parameter: %s" argType.FullName
let callFoo (ty : System.Type) =
let genericFoo =
typeof<Blah>.GetMethod "Foo"
let concreteFoo =
genericFoo.MakeGenericMethod [| ty |]
concreteFoo.Invoke (null, Array.empty);; // The ;; is only needed for F# interactive
Run Code Online (Sandbox Code Playgroud)
输出:
> callFoo typeof<int>;;
You called Foo with the type parameter: System.Int32
val it : obj = null
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1166 次 |
| 最近记录: |