F# 重载构造函数而不初始化

F# 重载构造函数而不初始化,f#,F#,我正在编写一个具有两个构造函数的泛型类:第一个构造函数初始化每个字段,第二个(无参数)不应初始化任何内容 我发现实现这一点的唯一方法是使用“empty”参数调用主构造函数,即Guid.empty和null。除了在我未经培训的人看来不是很好的函数风格之外,这意味着我必须在第二个参数上设置一个a':null约束,这是我不想要的: type Container<'a when 'a : null>(id : Guid, content : 'a) = let mutable _id

我正在编写一个具有两个构造函数的泛型类:第一个构造函数初始化每个字段,第二个(无参数)不应初始化任何内容

我发现实现这一点的唯一方法是使用“empty”参数调用主构造函数,即Guid.empty和null。除了在我未经培训的人看来不是很好的函数风格之外,这意味着我必须在第二个参数上设置一个
a':null
约束,这是我不想要的:

type Container<'a when 'a : null>(id : Guid, content : 'a) =
    let mutable _id = id
    let mutable _content = content

    new() = Container<'a>(Guid.Empty, null)

    member this.Id
        with get() = _id
        and set(value) = _id <- value

    member this.Content
        with get() = _content
        and set(value) = _content <- value
类型容器(id:Guid,内容:'a)=
设可变_id=id
设可变内容=内容
new()=ContainerF#模拟
default
未选中。default
。也可以使用不初始化的显式字段:

type Container<'a>() =
    [<DefaultValue>]
    val mutable _id : Guid
    [<DefaultValue>]
    val mutable _content : 'a

    new (id, content) as this =
        new Container<'a>() then
        this._id <- id
        this._content <- content

type Container如果该类型将从F#以外的语言中使用,那么下面提供了一个自然接口,例如F#和C#

type Container<'a>(?id : Guid, ?content : 'a) =
    let orDefault value = defaultArg value Unchecked.defaultof<_>
    let mutable _id = id |> orDefault
    let mutable _content = content |> orDefault

    new() = Container(?id = None, ?content = None)
    new(id : Guid, content : 'a) = Container<_>(?id = Some id, ?content = Some content)

    member this.Id
        with get() = _id
        and set(value) = _id <- value

    member this.Content
        with get() = _content
        and set(value) = _content <- value
类型容器或默认值
设可变_content=content |>orDefault
new()=容器(?id=None,?content=None)
新的(id:Guid,content:'a)=容器(?id=Some-id,?content=Some-content)
成员:这个
使用get()=\u id

和set(value)=\u id是否会从其他语言使用此类型?如果不是,您可以使用选项类型并避免未选中
。defaultof
。是的,这个类是作为从C使用的库的一部分公开的。我知道我的方法对于F不是很习惯,原因是这个类是从C使用的库的一部分。我会考虑去除变异性,因为在这种情况下,它可能根本不需要。标记丹尼尔的答案,因为它确实是我所需要的,但这也是一个很好。谢谢很不错的!适合我的需要,因为该类是从C#开始使用的。该类还通过需要无参数构造函数的外部库(用C#编写)进行序列化,因此我想我无论如何都需要这两个重载。
type 'a Container = { id : Guid; content : 'a } 

[<GeneralizableValue>]
let emptyContainer<'a> : 'a Container = 
    { id = Guid.Empty; 
      content = Unchecked.defaultof<_> }

let someOtherContainer = { emptyContainer with content = 12 }
type Container<'a>(?id : Guid, ?content : 'a) =
    let orDefault value = defaultArg value Unchecked.defaultof<_>
    let mutable _id = id |> orDefault
    let mutable _content = content |> orDefault

    new() = Container(?id = None, ?content = None)
    new(id : Guid, content : 'a) = Container<_>(?id = Some id, ?content = Some content)

    member this.Id
        with get() = _id
        and set(value) = _id <- value

    member this.Content
        with get() = _content
        and set(value) = _content <- value
new(id : Guid, content : 'a) = Container<_>(?id = Some id, ?content = Some content)
new() = Container()