【问题标题】:Calling generic function with instance of type使用类型实例调用泛型函数
【发布时间】:2013-02-03 13:42:26
【问题描述】:

我已经为这个问题苦苦挣扎了一段时间,似乎找不到任何解决方案。让我为你简化一下。

我有一个我想调用的通用函数,但我想调用它的类型参数仅作为一个实例。示例

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# 中,我会反映 foo_a 的 MethodInfo 并执行 MakeGenericMethod(t),但在 F# 中如何执行此操作?

只是为了清除,翻转依赖并让 foo_a 调用 foo_b 代替,对我来说不是一个选择。

【问题讨论】:

  • 反射在 F# 中的工作方式与在 C# 中的工作方式相同。你试过用那个吗?
  • 您能添加您的解决方案吗?

标签: generics f#


【解决方案1】:

正如@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

【讨论】:

  • 谢谢。我的问题是通过将我的代码放在一个类的静态成员中并对该类进行反射来解决的,如您的示例所示。需要有人跳出我的框框思考。 :)
  • 是否有可行的解决方案,仅从函数值开始,而不是类型+名称?
猜你喜欢
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 2013-10-03
相关资源
最近更新 更多