2

我正在尝试将 F# 集成为脚本语言,但FsiEvaluationSession.AddBoundVariable方法有问题。问题是这个方法创建了对象实际类型的变量,但我需要创建它实现的接口变量。我找不到AddBoundVariable<T>(string, T)或任何其他允许这样做的重载。

// located in common assembly
type IFoo =
    abstract Foo : unit -> unit

type FooImpl() =
    interface IFoo with
        member _.Foo () = ()

// located in host
session.AddBoundVariable ("foo", Foo())

session.EvalInteraction "foo.Foo()" // throws, `FooImpl` type doesn't have `Foo` method

session.EvalInteraction """
let foo : IFoo = foo
foo.Foo()
""" // throws, `IFoo` not found

问题是:如何创建我想要的类型变量?

4

1 回答 1

2

您必须将Foo实例显式转换为IFoo,所以这应该有效:

session.EvalInteraction """
let foo = foo :> IFoo
foo.Foo()
"""

为避免 FSI 的间接性,您可以在编译的代码中尝试此操作,只需foo先正常绑定即可:

let foo = FooImpl()
let foo : IFoo = foo    // ERROR: This expression was expected to have type 'IFoo' but here has type 'FooImpl'
let foo = foo :> IFoo   // works fine
foo.Foo()
于 2021-08-26T18:32:02.570 回答