let trees2 = formatter.Deserialize(fso) :?> Tree[]
Serializing Array of Binary Trees
-
26-06-2023 - |
Вопрос
The following code creates an array of simple binary trees and attempts to serialize and deserialize it. However, I don't know how to convert the object created by formatter.Deserialize(fso) back to an array of trees. I just get the error "This expression was expected to have type Tree array but here has type obj."
type Tree = | Branch of (string*float)*(Tree*Tree)
| Leaf of float
let trees = [|Branch (("x1", 0.), (Leaf 0., Leaf 1.)); Branch (("x2", 0.), (Leaf 0., Leaf 1.))|]
//Serialize
let filename = "C:/tree.dat"
let fs = new FileStream(filename, FileMode.Create)
let formatter = new BinaryFormatter()
formatter.Serialize(fs, trees)
fs.Close()
//Deserialize
let fso = new FileStream(filename, FileMode.Open)
let (trees2:array<Tree>) = formatter.Deserialize(fso)
fso.Close()
Решение
Другие советы
The result of formatter.Deserialize
is obj
which doesn't match the type array<Tree>
, and so you need a downcast:
...
let trees2 = formatter.Deserialize(fso) :?> array<Tree>
or
let (trees2:array<Tree>) = downcast formatter.Deserialize(fso)
Не связан с StackOverflow