Вопрос

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#?

Это было полезно?

Решение

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()

Другие советы

How about, for this particular interface:

using (var x = new Foo()) {
    ...
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top