Lần đầu tiên chơi với serialization trong C# ... bất kỳ trợ giúp nào sẽ được đánh giá cao! Sau đây là serializer chung của tôi và deserializer:Serialize/Deserialze thành chuỗi C#
public static string SerializeObject<T>(T objectToSerialize)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream memStr = new MemoryStream();
try
{
bf.Serialize(memStr, objectToSerialize);
memStr.Position = 0;
return Convert.ToBase64String(memStr.ToArray());
}
finally
{
memStr.Close();
}
}
public static T DeserializeObject<T>(string str)
{
BinaryFormatter bf = new BinaryFormatter();
byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
MemoryStream ms = new MemoryStream(b);
try
{
return (T)bf.Deserialize(ms);
}
finally
{
ms.Close();
}
}
Đây là đối tượng tôi đang cố gắng để serialize:
[Serializable()]
class MatrixSerializable : ISerializable
{
private bool markerFound;
private Matrix matrix;
public MatrixSerializable(Matrix m, bool b)
{
matrix = m;
markerFound = b;
}
public MatrixSerializable(SerializationInfo info, StreamingContext ctxt)
{
markerFound = (bool)info.GetValue("markerFound", typeof(bool));
matrix = Matrix.Identity;
if (markerFound)
{
//deserialization code
}
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
// serialization code
}
public Matrix Matrix
{
get { return matrix; }
set { matrix = value; }
}
public bool MarkerFound
{
get { return markerFound; }
set { markerFound = value; }
}
}
Và một ví dụ về cách đang chạy nó:
MatrixSerializable ms = new MatrixSerializable(Matrix.Identity * 5, true);
string s = Serializer.SerializeObject<MatrixSerializable>(ms);
Console.WriteLine("serialized: " + s);
ms = Serializer.DeserializeObject<MatrixSerializable>(s);
Console.WriteLine("deserialized: " + ms.Matrix + " " + ms.MarkerFound);
Khi tôi cố gắng chạy điều này, tôi nhận được một lỗi "SerializationException được unhandled: Dòng đầu vào không phải là một định dạng nhị phân hợp lệ. Các nội dung bắt đầu (theo byte) là: 41-41-45-41-41-41-44-2F- 2 F-2F-2F-2F-41-51-41-41-41 ... "
Bất kỳ lời khuyên nào về những gì tôi đang làm sai hoặc cách sửa lỗi này sẽ được đánh giá cao!
Ông có thể [cố gắng cắt bỏ mã boilerplate] (http://meta.stackexchange.com/a/129787/156418) từ này? Nó sẽ làm cho nó dễ đọc hơn. –