: ISerializable where T : class
+ {
+ ///
+ /// The item being wrapped.
+ ///
+ /// If this is null, that means we failed to serialize or deserialize it.
+ ///
+ private T m_item;
+
+ ///
+ /// A string useful for debugging the error.
+ ///
+ /// This is null if m_item deserialized properly.
+ /// Otherwise, it will be derived off of m_item.ToString() when we
+ /// serialized.
+ ///
+ private string m_name;
+
+ ///
+ /// Store an item in such a way that it can be deserialized.
+ ///
+ /// It must not be null.
+ ///
+ public MaybeSerialize(T item)
+ {
+ if (item == null)
+ {
+ throw new System.ArgumentNullException("Trying to store a null");
+ }
+ m_item = item;
+ m_name = null;
+ }
+
+ ///
+ /// Get the underlying deserialized value, or throw an exception
+ /// if deserialiation failed.
+ ///
+ public T Value
+ {
+ get
+ {
+ if (m_item == null)
+ {
+ throw new SerializationException($"The .NET object underlying {m_name} no longer exists");
+ }
+ return m_item;
+ }
+ }
+
+ ///
+ /// Get a printable name.
+ ///
+ public string ToString()
+ {
+ if (m_item == null)
+ {
+ return $"(missing {m_name})";
+ }
+ else
+ {
+ return m_item.ToString();
+ }
+ }
+
+ ///
+ /// Implements ISerializable
+ ///
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (m_item == null)
+ {
+ // Save the name; this failed to reload in a previous
+ // generation but we still need to remember what it was.
+ info.AddValue("n", m_name);
+ }
+ else
+ {
+ // Try to save the item. If it fails, too bad.
+ try
+ {
+ info.AddValue("i", m_item);
+ }
+ catch(SerializationException _)
+ {
+ }
+
+ // Also save the name in case the item doesn't deserialize
+ info.AddValue("n", m_item.ToString());
+ }
+ }
+
+ ///
+ /// Implements ISerializable
+ ///
+ private MaybeSerialize(SerializationInfo info, StreamingContext context)
+ {
+ try
+ {
+ // Try to deserialize the item. It might fail, or it might
+ // have already failed so there just isn't an "i" to find.
+ m_item = (T)info.GetValue("i", typeof(T));
+ m_name = null;
+ }
+ catch (SerializationException _)
+ {
+ // Getting the item failed, so get the name.
+ m_item = null;
+ m_name = info.GetString("n");
+ }
+ }
+ }
+}
pFad - Phonifier reborn
Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies:
Alternative Proxy
pFad Proxy
pFad v3 Proxy
pFad v4 Proxy