It seems to me that I should know this, but for some reason ....
What is the preferred way to serialize a class that comes from a (possibly abstract) base class, without having to serialize the entire path to the tree? For example, you may not be able to control the class from which you are extracting, but want to use serialization to clone your object (and only your object, not the base).
For instance:
// This is a base class that is outside my control, which derives from // some other base class that I know "nothing" about public abstract class SomeBaseClass : SomeOtherBaseClass { private string mBaseProperty = "Base Property"; public string BaseProperty { get { return mBaseProperty; } set { mBaseProperty = value; } } } // This is the class that I do control [Serializable()] private class MyDerivedClass : SomeBassClass { // Assume normal constructors, etc. // Here are some properties private string mDerivedPropertyOne = String.Empty; private string DerivedPropertyOne { get { return mDerivedPropertyOne ; } set { mDerivedPropertyOne = value; } } private string mDerivedPropertyTwo = String.Empty; private string DerivedPropertyTwo { get { return mDerivedPropertyTwo ; } set { mDerivedPropertyTwo = value; } } // And now a quick-n-dirty Equals override public override bool Equals(object obj) { if (obj == null) return false; MyDerivedClass compareTo = obj as MyDerivedClass; if (compareTo == null) return false; return ((String.Compare(this.DerivedPropertyOne, compareTo.DerivedPropertyOne, true) == 0) && (String.Compare(this.DerivedPropertyTwo, compareTo.DerivedPropertyTwo, true) == 0) && } } // And while we're at it, here a simple clone found elsewhere on StackOverflow public static class ObjectClone { public static T Clone<T>(this T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
As written, this will throw a SerializationException, as SomeBaseClass is not marked as serializable.
source share