Reputation: 1
I would like change object to ISerializable at runtime. Something like
<!-- language: c# -->
var nonSerializeObject = new NonSerialize();
ISerializable mySerializeObject =
somethingforserializable.serialize(nonSerializeObject,TypeOfObject);
Upvotes: 0
Views: 792
Reputation: 21024
I'm sorry, but you can't add an interface at runtime.
Being able to put an object to implement ISerializable doesn't mean you could implement it correctly.
HOWEVER...
You could, with reflection, fetch all the fields of a class and serialize it manually. Maybe by putting it inside a generic class that would serve as serializable envelope.
Something like this:
public class SerializableEnvelope<T> : ISerializable
{
private T item;
public T Item
{
get { return item; }
}
public SerializableEnvelope(T _item)
{
item = _item;
}
public SerializableEnvelope(SerializationInfo info, StreamingContext context)
{
item = Activator.CreateInstance<T>();
FieldInfo[] fields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo field in fields)
field.SetValue(item, info.GetValue(field.Name, field.FieldType));
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
FieldInfo[] fields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo field in fields)
info.AddValue(field.Name, field.GetValue(item));
}
}
Now, I haven't tried it, and it might not works fully with some classes that would store data in unusual way. For example, I'm only fetching the private fields, while some class may have public fields. (Unusual, but can happen)
You could also get some problem with nested object if they are also not serializable. But, you could detect that and create envelope automatically and rebuild the hierarchy on deserialization.
Upvotes: 2
Reputation: 31203
You cannot add attributes or interfaces/classes they derive from runtime. Though depending on how you serialize, they might not even be needed.
Upvotes: 1
Reputation: 21495
Not possible. Your best bet is to use XML serialization or implement your own serialization functions that use reflection to read all fields from the object (just note that reflection only returns private fields for the current type so you will have to manually traverse up the type hierarchy).
Your starting point would be nonSerializeObject.GetType().GetFields()
method.
Upvotes: 2
Reputation: 11750
You could create a class that can serialize (convert to some other representation) an object, but there's no way to add an interface (such as ISerializable
) to a class at runtime.
The System.Xml.Serialization.XMLSerializer
class can serialize your class without it implementing ISerializable
or being [Serializable]
.
Upvotes: 2