gpt4 book ai didi

generics - 使用类型实例调用泛型函数

转载 作者:行者123 更新时间:2023-12-02 22:01:47 25 4
gpt4 key购买 nike

我已经被这个问题困扰了很长一段时间,但似乎找不到任何解决方案。让我为您简化一下。

我有一个想要调用的通用函数,但我只想将其类型参数作为实例来调用。示例

let foo_a<'a> () = typeof<'a>
let foo_b (t : System.Type) = foo_a<t>() // of course this does not work

我希望以下陈述为真

foo_a<int>() = foo_b(typeof<int>)

在 C# 中,我会反射(reflect) 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

输出:

> callFoo typeof<int>;;
You called Foo with the type parameter: System.Int32
val it : obj = null

关于generics - 使用类型实例调用泛型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com