【问题标题】:Addressing interface conflicts in F#解决 F# 中的接口冲突
【发布时间】:2017-12-18 20:40:15
【问题描述】:

我想在 F# 中实现此处描述的解决方案: Inheritance from multiple interfaces with the same method name

具体来说,在 F# 中,如何解决在两个接口之间实现同名的接口函数?

这里是 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");
    }
}

【问题讨论】:

    标签: .net inheritance f#


    【解决方案1】:

    在 F# 中,接口始终是显式实现的,因此这甚至不是需要解决的问题。无论方法名称是否相同,这都是实现这些接口的方式:

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

    当您考虑到 F# 中接口方法的访问也是显式的时,这是有道理的。如果您有Dual,则不能调用Test 方法。您必须先向上转换为ITestITest2

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

    请注意,有一个安全的向上转换运算符 :> 用于以一种保证在编译时工作且不会导致运行时异常的方式转换对象层次结构。

    有时这种显式方法访问不方便,但我相信它会简化类型系统,从而使更多类型推断成为可能,并提高整体的便利性和安全性。

    【讨论】:

    • 感谢您的回复。这让我意识到我的问题更加微妙,因为我有一个从单个抽象接口 A 继承的类型,但是 A 实现了两个抽象接口 B 和 C,它们都共享一个公共方法名称。无论如何,通过在我的类型定义中显式实现底层接口,您的解决方案似乎也适用于这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    相关资源
    最近更新 更多