使用隐式构造函数将StructLayout属性添加到F#类型

时间:2012-10-31 09:19:46

标签: .net f# structlayout

我有:

type Package =
    abstract member Date : int
    abstract member Save : unit -> unit

[<type:StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)>]
type Instant(date : int, value : int) =
    let mutable _date = date
    let mutable _value = value
    member X.Value : int = _value
    interface Package with    
        member X.Date : int = _date
        member X.Save() = ...

但是得到错误:只有没有隐式构造函数的结构和类可以被赋予'StructLayout'属性

所以我意识到它必须是相似的东西:

type Instant =
    struct
        val Date : byte array
        ...

但这样我丢失了界面。在C#中,例如,对于这种类型的类,可以添加type:StructLayout(我认为)。我如何重构代码以避免此错误?

1 个答案:

答案 0 :(得分:5)

正如错误消息所述,StructLayout应与explicit constructors合作:

type Package =
    abstract member Date : int
    abstract member Save : unit -> unit

[<type:StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)>]
type Instant =
    val mutable Date: int
    val mutable Value: int
    new(date, value) = {Date = date; Value = value}

    interface Package with
        member x.Date = x.Date
        member x.Save() = x.Value |> ignore

如果您对FieldOffset有任何进一步的问题,请查看代码示例here