How can I serialize an object containing an interface?
I was thinking i could inherit from ISerializable and have GetObjectData determine the type at runtime, and serialize that. unfortunatly i receive an error creating the XMLSerializer
cannot serialize the object because it contains an Interface.
is it possible to get around this and still use the XMLserializer?
here is some example code:
public interface MyInterface
{
void DoStuff();
}
public class DataTypeInt : MyInterface
{
public int data = 0;
#region MyInterface Members
public void DoStuff()
{
}
#endregion
}
public class DataTypeString : MyInterface
{
public string data;
#region MyInterface Members
public void DoStuff()
{
}
#endregion
}
public class MyObject : ISerializable
{
public MyInterface data;
public MyObject()
{
}
public MyObject(SerializationInfo info, StreamingContext context)
{
string type =(string) info.GetValue("type", typeof(string));
if (type == "DataTypeInt")
{
DataTypeInt MyData = new DataTypeInt();
MyData.data = (int)info.GetValue("data", typeof(int));
data = MyData;
}
else if (type == "DataTypeString")
{
DataTypeString MyData = new DataTypeString();
MyData.data = (string)info.GetValue("data", typeof(string));
data = MyData;
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
Type type = data.GetType();
if (type == typeof(DataTypeInt))
{
info.AddValue("type", "DataType");
DataTypeInt myData = data as DataTypeInt;
info.AddValue("data", myData.data);
}
else if (type == typeof(DataTypeString))
{
info.AddValue("type", "DataTypeTwo");
DataTypeString myData = data as DataTypeString;
info.AddValue("data", myData.data);
}
}
}