I have an object which has a IPEndPoint member but, since it has no parameterless constructor, I get an error when I try to serialize it through reflection.
I have to serialize a list of NetAudioDispatcher objects....this is the code:
[XmlType(TypeName = "CLanReceiverInfo")]
public class CLanReceiverInfo : ISerializable
{
public IPEndPoint RxEndPoint;
public List<IPEndPoint> TxEndPoints;
public CLanReceiverInfo()
{
RxEndPoint = new IPEndPoint(IPAddress.Loopback, 5000);
TxEndPoints = new List<IPEndPoint>(1){ new IPEndPoint(IPAddress.Loopback, 6000) };
}
public CLanReceiverInfo(SerializationInfo info, StreamingContext context)
{
try
{
// Reset the property value using the GetValue method.
RxEndPoint = (IPEndPoint)info.GetValue("RxEndPoint", typeof(IPEndPoint));
TxEndPoints = (List<IPEndPoint>)info.GetValue("TxEndPoints", typeof(List<IPEndPoint>));
}
catch (Exception)
{
RxEndPoint = new IPEndPoint(IPAddress.Loopback, 5000);
TxEndPoints = new List<IPEndPoint>(1){ new IPEndPoint(IPAddress.Loopback, 6000) };
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("RxEndPoint", RxEndPoint);
info.AddValue("TxEndPoints", TxEndPoints);
}
}
[XmlType(TypeName = "NetAudioDispatcher")]
public class NetAudioDispatcher : ISerializable
{
public CLanReceiverInfo ReceiverInfo { get; private set; }
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ReceiverInfo", ReceiverInfo);
}
public NetAudioDispatcher()
{
ReceiverInfo = new CLanReceiverInfo();
}
public NetAudioDispatcher(SerializationInfo info, StreamingContext context)
{
try
{
ReceiverInfo = (CLanReceiverInfo)info.GetValue("ReceiverInfo", typeof(CLanReceiverInfo));
}
catch (Exception)
{
ReceiverInfo = new CLanReceiverInfo();
}
}
}
[XmlRoot("NetAudioDispatchers")]
public class NetAudioDispatchers
{
[XmlElement("NetAudioDispatcher")]
public List<NetAudioDispatcher> Items { get; set; }
public NetAudioDispatchers()
{
Items = new List<NetAudioDispatcher>();
}
}
And to (de)serialize:
var xmlSerializer = new XmlSerializer(typeof(NetAudioDispatchers));
StreamReader stream = new StreamReader(NetworkChatDemo.Properties.Settings.Default.NetAudioDispatchers);
dispatchers = (NetAudioDispatchers)xmlSerializer.Deserialize(stream);
Is there a way to overtake this? Or I have to change my class design?