从 C# 调用 F# 对象的接口方法

发布于 2024-12-10 16:44:11 字数 601 浏览 0 评论 0原文

给定 F# 类型:

type Foo() =
    member this.Prop with get() = ()

    interface IDisposable with
        member this.Dispose() = ()

在 C# 中,我创建对象,但无法调用 Dispose():

var x = new Foo();
x.Dispose(); // compile error, x does not contain a definition of Dispose

但是,我可以写:

((IDisposable)x).Dispose(); // works, but I don't like the cast

有什么方法可以避免 C# 中的强制转换吗?这是否与 F# 不会自动让您从 F# 中调用 Foo 类型上的 .Dispose() 相关?

Given an F# type:

type Foo() =
    member this.Prop with get() = ()

    interface IDisposable with
        member this.Dispose() = ()

In C#, I create the object, but I can't call Dispose():

var x = new Foo();
x.Dispose(); // compile error, x does not contain a definition of Dispose

However, I can write:

((IDisposable)x).Dispose(); // works, but I don't like the cast

Is there any way to avoid the cast in C#? Is this related to the way F# doesn't automatically let you call .Dispose() on the Foo type from within F#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

想念有你 2024-12-17 16:44:11

默认情况下,F# 中的接口实现是显式的。因此,除非从转换为接口的类型(某种形式的转换)中看到,否则这些方法是不可见的。

要解决此问题,请公开一个与接口版本具有相同签名的实例方法。然后将接口转发到实例函数。例如

type Foo() =
    member this.Prop with get() = ()
    member this.Dispose() = ()

    interface IDisposable with
        member this.Dispose() = this.Dispose()

Interface implementations in F# are explicit by default. Hence the methods are not visible unless seen from the type converted to the interface (some form of casting).

To work around this expose an instance method which has the same signature as the interface version. Then have the interface on forward to the instance function. For example

type Foo() =
    member this.Prop with get() = ()
    member this.Dispose() = ()

    interface IDisposable with
        member this.Dispose() = this.Dispose()
吾性傲以野 2024-12-17 16:44:11

对于这个特定的接口怎么样:

using (var x = new Foo()) {
    ...
}

How about, for this particular interface:

using (var x = new Foo()) {
    ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文