从 C# 调用 F# 对象的接口方法
给定 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,F# 中的接口实现是显式的。因此,除非从转换为接口的类型(某种形式的转换)中看到,否则这些方法是不可见的。
要解决此问题,请公开一个与接口版本具有相同签名的实例方法。然后将接口转发到实例函数。例如
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
对于这个特定的接口怎么样:
How about, for this particular interface: