Giả sử tôi có một kiểu giá trị bất biến như thế này:Làm thế nào để sử dụng protobuf-net với các loại giá trị bất biến?
[Serializable]
[DataContract]
public struct MyValueType : ISerializable
{
private readonly int _x;
private readonly int _z;
public MyValueType(int x, int z)
: this()
{
_x = x;
_z = z;
}
// this constructor is used for deserialization
public MyValueType(SerializationInfo info, StreamingContext text)
: this()
{
_x = info.GetInt32("X");
_z = info.GetInt32("Z");
}
[DataMember(Order = 1)]
public int X
{
get { return _x; }
}
[DataMember(Order = 2)]
public int Z
{
get { return _z; }
}
public static bool operator ==(MyValueType a, MyValueType b)
{
return a.Equals(b);
}
public static bool operator !=(MyValueType a, MyValueType b)
{
return !(a == b);
}
public override bool Equals(object other)
{
if (!(other is MyValueType))
{
return false;
}
return Equals((MyValueType)other);
}
public bool Equals(MyValueType other)
{
return X == other.X && Z == other.Z;
}
public override int GetHashCode()
{
unchecked
{
return (X * 397)^Z;
}
}
// this method is called during serialization
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("X", X);
info.AddValue("Z", Z);
}
public override string ToString()
{
return string.Format("[{0}, {1}]", X, Z);
}
}
Nó hoạt động với BinaryFormatter hoặc DataContractSerializer nhưng khi tôi cố gắng sử dụng nó với protobuf-net (http://code.google.com/p/protobuf-net/) serializer tôi nhận được lỗi này:
Cannot apply changes to property ConsoleApplication.Program+MyValueType.X
Nếu tôi áp dụng setters cho các thuộc tính được đánh dấu với thuộc tính DataMember nó sẽ làm việc nhưng sau đó nó phá vỡ bất biến của loại giá trị này và đó là không mong muốn cho chúng tôi.
Có ai biết tôi cần làm gì để nó hoạt động không? Tôi đã nhận thấy rằng có một quá tải của phương thức ProtoBu.Serializer.Serialize lấy một SerializationInfo và một StreamingContext nhưng tôi đã không sử dụng chúng bên ngoài bối cảnh triển khai thực hiện giao diện ISerializable, vì vậy bất kỳ ví dụ mã nào về cách sử dụng chúng trong bối cảnh này sẽ được nhiều người đánh giá cao!
Cảm ơn,
EDIT: vì vậy tôi đào lên một số bài viết cũ MSDN và có một sự hiểu biết tốt hơn về địa điểm và cách SerializationInfo và StreamingContext được sử dụng, nhưng khi tôi đã cố gắng để làm điều này:
var serializationInfo = new SerializationInfo(
typeof(MyValueType), new FormatterConverter());
ProtoBuf.Serializer.Serialize(serializationInfo, valueType);
nó chỉ ra rằng các phương pháp Serialize<T>
chỉ cho phép các loại tài liệu tham khảo, là có một lý do cụ thể cho điều đó? Có vẻ hơi lạ khi tôi có thể sắp xếp các loại giá trị được hiển thị thông qua loại tham chiếu.
Xin lỗi vì sự chậm trễ - cuối tuần bận rộn –