可序列化的FSharp对象异常

时间:2011-11-21 19:43:06

标签: serialization f#

我有一个必须序列化的F#类。

为了显示我的问题,我把它变成了大量的:

[<Serializable>]
type TestValidator(min) =
    let Test value = 
        min < value

当我想序列化/反序列化时,我收到以下错误消息: 二进制流“0”不包含有效的BinaryHeader。可能的原因是序列化和反序列化之间的无效流或对象版本更改。

要序列化的我的C#示例代码:

var test = new Validator.TestValidator(0);
var ser = CodeHelper.ByteUtils.BinarySerializeObject(test);
var deser = CodeHelper.ByteUtils.BinaryDeSerializeObject(ser.Generic);

CodeHelper.ByteUtils.BinarySerializeObject:

   public static DetailedBoolObjectRet<byte[]> BinarySerializeObject(object input)
    {
        try
        {
            var ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, input);
            byte[] bytes = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(bytes, 0, bytes.Length);

            return new DetailedBoolObjectRet<byte[]>(bytes, true);
        }
        catch (System.Exception exc)
        {
            Debug.Assert(false, exc.Message);
            return new DetailedBoolObjectRet<byte[]>(null, false, exc.Message);
        }
    }

 public static DetailedBoolObjectRet<object> BinaryDeSerializeObject(byte[] input)
    {
        try
        {
            var ms = new MemoryStream(input);
            BinaryFormatter formatter = new BinaryFormatter();
            var deserialized = formatter.Deserialize(ms);

            return new DetailedBoolObjectRet<object>(deserialized, true);
        }
        catch (System.Exception exc)
        {
            Debug.Assert(false, exc.Message);
            return new DetailedBoolObjectRet<object>(null, false, exc.Message);
        }
    }

序列化会出现什么问题?

1 个答案:

答案 0 :(得分:1)

我刚刚把测试组合在一起

open System
open System.IO
open System.Runtime.Serialization.Formatters.Binary

[<Serializable>]
type TestValidator(min) =
    let Test value = 
        min < value


let test = new TestValidator(0)
let ms = new MemoryStream()
let formatter = new BinaryFormatter()
formatter.Serialize(ms, test)
let bytes = Array.init (int ms.Length) (fun i -> byte 0x00)
ms.Position <- int64 0
ms.Read(bytes,0,int ms.Length)

let des =
    let ms = new MemoryStream(bytes)
    let formatter = new BinaryFormatter()
    formatter.Deserialize(ms) :?> TestValidator

似乎工作正常......也许“DetailedBoolObjectRet”存在问题?您获得的异常可以通过尝试反序列化0x00数组来重现。

编辑:

如果您的问题严格依据C#,请尝试

[<Serializable>]
type TestValidator(min:int) =
    let Test value = 
        min < value

虽然这可能不是你想要的......