扩展属性不可变是很奇怪的...... 有人可以帮忙吗?
open System.IO.Ports
open System.Text
open System.Text.RegularExpressions
type UAgent<'T> = MailboxProcessor<'T>
module ComPortManager =
type MailboxProcessor<'T> with
member this.sP = ref(new SerialPort("0"))
member this.receivedSeq : byte [] = Array.empty
member this.pastMsgSent : seq<string> = Seq.empty
type Cmd =
| Send = 0
| Remove = 1
| Add = 2
type UartOP =
| Open of unit
| Comm of Cmd * string
| Handler of Cmd * SerialDataReceivedEventHandler
let CreateComPort =
fun pN bR (p : System.IO.Ports.Parity) dB (sB : System.IO.Ports.StopBits) to' handler ->
match Array.exists (fun a -> a = pN) (SerialPort.GetPortNames()) with
| false -> failwith "Not valid comport!"
| _ -> ()
let mutable agent : UAgent<UartOP> =
UAgent.Start(handler)
let mutable sP = new SerialPort(pN)
agent.sP := sP
agent.sP.contents.Close()
match agent.sP.contents <> null with
| true ->
agent.sP.contents.Close()
| false ->
()
agent.sP.contents.BaudRate <- bR
printfn "\r\n=o==> %s" (bR.ToString())
printfn "\r\n=o==> %s" (sP.BaudRate.ToString())
printfn "\r\n=o==> %s" (agent.sP.contents.BaudRate.ToString())
agent.sP.contents.Parity <- p
agent.sP.contents.DataBits <- dB
agent.sP.contents.StopBits <- sB
agent.sP.contents.ReadTimeout <- to'
agent
变量sP的属性内容的波特率在尝试将其设置为bR后不会改变...
输出如下:
= O ==&GT; 19200
= O ==&GT; 9600
= O ==&GT; 9600
答案 0 :(得分:3)
你试图这样做的方式是行不通的。在F#中,扩展无法向现有类型添加新字段,因此您无法真正添加其他可变状态。
你的定义是做的是它添加了一堆只读属性,这些属性总是返回一个新值(sP
时为新的引用单元格,{{1}时为新数组}})。每次调用receivedSeq
时,它都会创建一个新值并将其返回(因此您最终会改变立即进行垃圾回收的新副本)。
要解决此问题,您需要创建一个新的类型来包装邮箱处理器并添加其他状态,这些都是这样的:
agent.sP