通用读/写字节数组

时间:2013-01-24 16:50:13

标签: c# .net

我希望能够将泛型变量放到字节数组中(用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>();
  

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

这有什么问题?

1 个答案:

答案 0 :(得分:0)

尝试将memorystream的position属性设置为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;
    }
}