问题
I have an object with a property implemented like
public String Bla {get;set;}
After changing the implementation to something like
private String _bla;
public String Bla
{
get { return _bla; }
set { _bla = value; }
}
on deserialzation, this Property comes up empty.
i have lots of serialized data from the old implementation, and would like to load them with the new implementation
is there any way, to change the implentation to be compatible with older binary files?
EDIT:
Some people might run into the same problem, so here's my hackish solution:
the autogenerated fields have a naming convention that is non-valid c# code:
[CompilerGenerated]
private string <MyField>k__BackingField;
[CompilerGenerated]
public void set_MyField(string value)
{
this.<MyField>k__BackingField = value;
}
[CompilerGenerated]
public string get_MyField()
{
return this.<MyField>k__BackingField;
}
the quick and dirty fix for me was to create a private backing field called xMyFieldxK__BackingField
in the source,
and patching the serialized binarydata by replacing all occurences of <MyField>
with xMyFieldx
before deserialisation
回答1:
Try implementing ISerializable
[SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("name of compiler generated field", _bla);
}
回答2:
The BinaryFormatter
serializes the fields, not the properties.
You could possibly get it to work by seeing what the auto-generated field name was in ILSpy or something similar and naming yours that way.
Otherwise as stated by Henrik you would have to write your own deserialization, see this question for more information
You can probably inspect the deserialization info by implementing ISerializable
and special case this field.
来源:https://stackoverflow.com/questions/13725025/change-auto-implemented-properties-to-normal-and-deserialization-with-binaryform