gpt4 book ai didi

.NET:如何对具有[DataContract]属性的对象进行二进制序列化?

转载 作者:行者123 更新时间:2023-12-04 04:46:48 27 4
gpt4 key购买 nike

标记为[DataContract]的类不能同时进行ISerializable。好的,如何将这种类型的对象序列化为二进制流?

private byte[] GetRoomAsBinary(Room room)
{
MemoryStream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, room);
return stream.ToArray();
}

没有Room可序列化,我无法使其正常工作。
如何从对象中获取字节数组?

最佳答案

使用二进制格式化程序进行序列化和反序列化的代码:

public static class BinarySerializer
{
public static byte[] Serialize<T>(T obj)
{
var serializer = new DataContractSerializer(typeof(T));
var stream = new MemoryStream();
using (var writer =
XmlDictionaryWriter.CreateBinaryWriter(stream))
{
serializer.WriteObject(writer, obj);
}
return stream.ToArray();
}

public static T Deserialize<T>(byte[] data)
{
var serializer = new DataContractSerializer(typeof(T));
using (var stream = new MemoryStream(data))
using (var reader =
XmlDictionaryReader.CreateBinaryReader(
stream, XmlDictionaryReaderQuotas.Max))
{
return (T)serializer.ReadObject(reader);
}
}
}

用法:
public void TestBinarySerialization()
{
// Create the person object.
Person person = new Person { Name = "John", Age = 32 };

// Serialize and deserialize the person object.
byte[] data = BinarySerializer.Serialize<Person>(person);
Person newPerson = BinarySerializer.Deserialize<Person>(data);

// Assert the properties in the new person object.
Debug.Assert(newPerson.Age == 32);
Debug.Assert(newPerson.Name == "John");
}

关于.NET:如何对具有[DataContract]属性的对象进行二进制序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2383380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com