gpt4 book ai didi

F# 向上转换基础

转载 作者:行者123 更新时间:2023-12-01 10:56:04 25 4
gpt4 key购买 nike

当我想将 base 向上转换为适当的接口(interface)类型(即 A)以便我可以在其上调用 doA() 时,我遇到了一个解析错误。我知道 base ( http://cs.hubfs.net/topic/None/58670 ) 有些特殊,但到目前为止我还没有找到解决这个特定问题的方法。

有什么建议吗?

type A =
abstract member doA : unit -> string

type ConcreteA() =
interface A with
member this.doA() = "a"

type ExtA() =
inherit ConcreteA()


interface A with
override this.doA() = "ex" // + (base :> A).doA() -> parse error (unexpected symbol ':>' in expression)

((new ExtA()) :> A).doA() // output: ex

工作的 C# 等价物:

public interface A
{
string doA();
}

public class ConcreteA : A {
public virtual string doA() { return "a"; }
}

public class ExtA : ConcreteA {
public override string doA() { return "ex" + base.doA(); }
}

new ExtA().doA(); // output: exa

最佳答案

这相当于您的 C#:

type A =
abstract member doA : unit -> string

type ConcreteA() =
abstract doA : unit -> string
default this.doA() = "a"
interface A with
member this.doA() = this.doA()

type ExtA() =
inherit ConcreteA()
override this.doA() = "ex" + base.doA()

ExtA().doA() // output: exa

base 不能单独使用,只能用于成员访问(因此会出现解析错误)。请参阅 Classes on MSDN 下的指定继承 .

关于F# 向上转换基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15033448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com