F# and interface-implemented members

后端 未结 2 1643
闹比i
闹比i 2020-12-31 05:42

I have a vexing error.

type Animal =

    abstract member Name : string

type Dog (name : string) =

    interface Animal with

        member this.Name : st         


        
相关标签:
2条回答
  • 2020-12-31 06:32

    Another option is to use an abstract class instead of an interface:

    [<AbstractClass>]
    type Animal () =
        abstract Name : string
    
    type Dog (name) = 
        inherit Animal()
        override dog.Name = name
    
    let pluto = Dog("Pluto")
    let name = pluto.Name
    
    0 讨论(0)
  • 2020-12-31 06:42

    In F#, when you implement an interface, it's an equivalent of explicit interface implementation in C#. That is, you can call the method through the interface, but not directly through the class.

    F# reference article about interfaces suggests adding a method that does the upcasting to the type:

    type Dog (name : string) =
    
        member this.Name = (this :> Animal).Name
    
        interface Animal with
            member this.Name : string = name
    

    Or, as suggested by Daniel, you can do it the other way around, which means you can avoid that cast:

    type Dog (name : string) =
    
        member this.Name = name
    
        interface Animal with
            member this.Name : string = this.Name
    

    Also, the .Net convention for interface names is to start them with I, so your interface should be called IAnimal.

    0 讨论(0)
提交回复
热议问题