F#中的多个构造函数和类继承

wan*_*gzq 7 f#

我很难将以下C#代码转换为F#:

class Foo
{
    public Foo() { }
    public Foo(string name) { }
}

class Bar : Foo
{
    public Bar() : base() { }
    public Bar(string name) : base(name) { }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我第一次尝试跟随,但报告错误

"Bar"类型的构造函数必须直接或间接调用其隐式对象构造函数.使用对隐式对象构造函数的调用而不是对记录表达式的调用.

type Foo() =
    new(name:string) = Foo()

type Bar() =
    inherit Foo()
    new(name:string) = { inherit Foo(name) }
    member val Name:string = null with get, set
Run Code Online (Sandbox Code Playgroud)

然后我试着跟随,但它现在报告auto属性的错误

'member val'定义仅允许在具有主构造函数的类型中使用.考虑为您的类型定义添加参数"

type Foo() =
    new(name:string) = Foo()

type Bar =
    inherit Foo
    new(name:string) = { inherit Foo(name) }
    member val Name:string = null with get, set
Run Code Online (Sandbox Code Playgroud)

Mar*_*ist 9

如果您希望F#源代码编译为 C#代码给出的API 完全相同的 API,则答案如下:

type Foo =
    new() = {}
    new(name:string) = { }

type Bar =
    inherit Foo

    [<DefaultValue>] 
    val mutable private name:string

    new() = { inherit Foo() }
    new(name) = { inherit Foo(name) }

    member x.Name with get() = x.name and set v = x.name <- v
Run Code Online (Sandbox Code Playgroud)