开发者

Is there easier way to work with F# mutable structures

开发者 https://www.devze.com 2023-04-08 10:58 出处:网络
How I do it now is really weird. And the sad thing is I\'ve got many structures and use them often. Here is how I\'m acting for a moment :

How I do it now is really weird. And the sad thing is I've got many structures and use them often.

Here is how I'm acting for a moment :

[<type:StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)>]
type OneDevice = {
        mutable id              : UInt16
        mutable typeDev         : byte
        mutable portNum         : byte
        mutable Parity          : byte
        mutable StopBits        : byte
        mutable BaudRate        : byte
        mutable addr1           : byte 
        mutable addr2           : byte 
        mutable useCanal        : byte
        mutable idGroup1        : byte
        mutable idGroup2        : byte 
        mutable idGroup3        : byte
        mutable idGroup4        : byte
        mutable idGroupSos1     : byte 
        mutable idGroupSos2     : byte 
        mutable idGroupSos3     : byte 
        mutable idGroupSos4     : byte 
        mutable idSosReserv     : byte 
        mutable addrModbus      : byte 
        mutable offsetModbus    : System.UInt16
        [<field: MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)>]
        mutable pwd             : byte array
        mutable offsetInModbus  : UInt16
        mutable reserv          : UInt16 }

Here is how I define structures. "type str = struct ... " works really different ! I need exactly my variant of structure. But writing this is just a half of my trouble, second half is how I create new element of this structure. let mutable dev = new OneDevice() doesn't work ! So I need to make this :

let mutable dev = {  
    id              = 0us 
    typeDev         = 0x00uy
    portNum         = 0x00uy
    Parity          = 0x00uy
    StopBits        = 0x00uy
    BaudRate        = 0x00uy
    addr1           = 0x00uy
    addr2           = 0x00uy
    useCanal        = 0x00uy
    idGroup1        = 0x00uy
    idGroup2        = 0x00uy
    idGroup3        = 0x00uy
    idGroup4        = 0x00uy
    idGroupSos1     = 0x00uy
    idGroupSos2     = 0x00uy
    idGroupSos3     = 0x00uy
    idGroupSos4     = 0x00uy
    i开发者_如何学PythondSosReserv     = 0x00uy
    addrModbus      = 0x00uy
    offsetModbus    = 0us
    pwd             = Array.zeroCreate 17
    offsetInModbus  = 0us
    reserv          = 0us }

And that is weirdest part here. Can I make it somehow easier ?

Thank you !


The problem is these are not structures. They're record types. Use type [<Struct>] MyStruct = ....

See http://msdn.microsoft.com/en-us/library/dd233233.aspx and http://msdn.microsoft.com/en-us/library/ee340416.aspx

Record types: http://msdn.microsoft.com/en-us/library/dd233184.aspx

Structs are value types. Records are reference types, like classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消