0

我希望能够将通用变量放入字节数组(使用 EF 将其保存到数据库中)

我试过这样:

public byte[] SerializedParams { get; set; } // property for EF

...

public void Write(params object[] args)
{
    var bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, args);

        SerializedParams = ms.ToArray();
    }
}

public T Read<T>()
{
    var byteSize = Marshal.SizeOf(typeof(T));
    using (var ms = new MemoryStream())
    {
        ms.Write(SerializedParams, 0, SerializedParams.Length);
        var bf = new BinaryFormatter();
        var x = bf.Deserialize(ms); // error here
        return (T)x;
    }
}

var x = bf.Deserialize(ms); 此行会导致错误。调用后:

qr.Write(5,7,9);
var i1 = qr.Read<int>(); // error here
var i2 = qr.Read<int>();
var i3 = qr.Read<int>();

“在解析完成之前遇到流结束。”

那有什么问题?

4

1 回答 1

0

尝试将内存流的位置属性设置为 0:

public T Read<T>()
{
    var byteSize = Marshal.SizeOf(typeof(T));
    using (var ms = new MemoryStream())
    {
        ms.Write(SerializedParams, 0, SerializedParams.Length);
        var bf = new BinaryFormatter();
        ms.Position = 0; // this line should do the trick
        var x = bf.Deserialize(ms); 
        return (T)x;
    }
}
于 2013-01-24T16:53:32.043 回答