简体   繁体   English

解决F#中的接口冲突

[英]Addressing interface conflicts in F#

I would like to implement the solution described here in F#: Inheritance from multiple interfaces with the same method name 我想在F#中实现此处描述的解决方案: 从具有相同方法名称的多个接口继承

Specifically, in F#, how do I address implementing interface functions that share the same name between two interfaces? 具体来说,在F#中,如何实现两个接口之间共享同名的接口函数的实现?

Here is the C# solution: 这是C#解决方案:

public interface ITest {
    void Test();
}
public interface ITest2 {
    void Test();
}
public class Dual : ITest, ITest2
{
    void ITest.Test() {
        Console.WriteLine("ITest.Test");
    }
    void ITest2.Test() {
        Console.WriteLine("ITest2.Test");
    }
}

In F#, interfaces are always implemented explicitly so this isn't even a problem that needs to be solved. 在F#中,接口始终是显式实现的,因此这甚至不是需要解决的问题。 This is how you would implement these interfaces whether or not the method names were the same: 无论方法名称是否相同,这都是您实现这些接口的方式:

type ITest =
    abstract member Test : unit -> unit

type ITest2 =
    abstract member Test : unit -> unit

type Dual() =
    interface ITest with
        member __.Test() = Console.WriteLine("ITest.Test")

    interface ITest2 with
        member __.Test() = Console.WriteLine("ITest2.Test")

This makes sense when you consider that access of interface methods in F# is also explicit. 当您考虑到F#中接口方法的访问也是显式的时,这是有意义的。 If you have a Dual you can't call the the Test method. 如果您有Dual ,则无法调用Test方法。 You must first upcast to either ITest or ITest2 : 您必须首先向ITestITest2

let func (d:Dual) = d.Test() // Compile error!

let func (d:Dual) =
    (d :> ITest).Test()
    (d :> ITest2).Test()
    // This is fine

Note that there is a safe upcast operator :> for casting up the object hierarchy in a way that is guaranteed to work at compile time, and cannot result in a run-time exception. 请注意,有一个安全的upcast运算符:>用于以保证在编译时工作的方式来转换对象层次结构,并且不会导致运行时异常。

Sometimes this explicit method access is inconvenient, but I believe it leads to a simplification of the type system that makes more type inference possible and increases convenience and safety overall. 有时这种显式方法访问不方便,但我相信这会导致类型系统的简化,从而使更多的类型推断成为可能,并提高整体的便利性和安全性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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