I had the following class:
[Serializable]
public class Message
{ public string messageSummary;
public DateTime messageDate;
}
Later, i decided to add to the class another int field - messageNumber
[Serializable]
public class Message
{
public string messageSummary;
public DateTime messageDate;
public int messageNumber;
}
In deserialization, when deserializing an old serialized Message
class(without messageNumber
field) - how can I set the default value of messageNumber to -1 instead of 0?
I tried to define a method with [OnDeserialized()]
attribute, but messageNumber
is already set there to 0. 0 can also the value of messageNumber
, so I can't override it in that method. Is it possible to set the default value to -1? Thanks
[OnDeserialized]
happens after deseralization. If you want to set default value you can define [OnDeserializing]
serialization callback
[OnDeserializing]
private void SetMessageNumberDefault(StreamingContext sc)
{
messageNumber = -1; // add default value
}
You can try DefaultValueAttribute as describe in this documentation . Than you can try solution as follow:
[Serializable]
public class Message
{
public const int Int_Default = -1;
public string messageSummary;
public DateTime messageDate;
[System.ComponentModel.DefaultValue(Int_Default)]
public int messageNumber { get; set; } = Int_Default;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.