質問

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()
役に立ちましたか?

解決

let trees2 = formatter.Deserialize(fso) :?> Tree[]

他のヒント

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top