简体   繁体   中英

implementing a C# interface in f#: can't get the type right

I have been experimenting with F#, and thought, as a learning exercise I could get an existing c# project and replace classes one by one with F# versions. I'm running into trouble when I try to implement a generic C# interface with a F# 'class' type.

C# interface

public interface IFoo<T> where T : Thing
    {
         int DoSomething<T>(T arg);
    }

trying to implement F#. I've had various versions, this is the closest (giving me the least amount of error messages)

type Foo<'T when 'T :> Thing> =
    interface IFoo<'T> with
        member this.DoSomething<'T>(arg) : int =
            45 

the compilation error I get now is:

The member 'DoSomething<'T> : 'T -> int' does not have the correct type to override the corresponding abstract method. The required signature is 'DoSomething<'T> : 'T0 -> int'.

this has me baffled. What is 'T0? More importantly how do I implement this member correctly?

Firstly, the generic parameter to DoSomething shadows the type parameter T on the IFoo<T> interface. You probably intend to use:

public interface IFoo<T> where T : Thing
{
    int DoSomething(T arg);
}

Once you do that, you can implement the interface with:

type Foo<'T when 'T :> Thing> =
    interface IFoo<'T> with
        member this.DoSomething arg = 45

If you did intend to shadow the type parameter on the C# interface, the above definition will still work and the compiler will infer the type of arg to be 'a instead of T :> Thing as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM