我有:
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
(我认为)。我如何重构代码以避免此错误?
答案 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。