【问题标题】:Bind variable to interface type in FSI将变量绑定到 FSI 中的接口类型
【发布时间】:2021-08-26 16:39:09
【问题描述】:

我正在尝试将 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

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

【问题讨论】:

    标签: f# f#-interactive fsi


    【解决方案1】:

    您必须将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()
    

    【讨论】:

    • 问题是session.AddBoundVariable 添加变量但没有将库添加到编译上下文。我必须使用session.EvalInteraction """#r "CommonLib.dll"""" 显式添加库,然后它才能工作。还是谢谢!
    • 很高兴知道,但与您提出的问题不同。无论如何,我很高兴你能弄明白。
    猜你喜欢
    • 2011-02-07
    • 2015-11-22
    • 2017-01-29
    • 2013-02-08
    • 1970-01-01
    • 2023-03-07
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多