I am looking for a way to ensure that only serializable objects are stored into a Dictionary in C#.
To be more specific I'm looking to do something similar to this:
Dictionary<String, ISerializable> serialDict = new Dictionary<String, ISerializable>();
The problem with this is that I cannot store primitive types like integers, booleans, or strings.
Is there a way to ensure that my Dictionary contains only objects which can be serialized?
Dictionary can't be serialized as a document.
Unity cannot serialize standard dictionaries. This means that they won't show or be edited in the inspector and they won't be instantiated at startup. A classic workaround is to store the keys and values in separate arrays and construct the dictionary at startup.
The serialization and deserialization of . NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy. For this, you have to create a special Dictionary class which is able to serialize itself.
The standard solution for serializing and deserializing a Python dictionary is with the pickle module. The dumps() function serialize a Python object by converting it into a byte stream, and the loads() function do the inverse, i.e., convert the byte stream back into an object.
I don't think you can do this at compile-time, but you can do it at runtime. If you build your own class deriving from Dictionary<TKey, TValue>
, then in the constructor of your class, you can check the attributes attached to the TValue
type, and make sure SerializableAttribute
is one of them, else throw an exception.
All of the standard primitive types (int
, bool
, etc.) have this attribute.
One thing to consider is that in classes that are serializable are tagged with the SerializableAttribute as opposed to implementing an interface. From MSDN:
Any class that might be serialized must be marked with the SerializableAttribute. If a class needs to control its serialization process, it can implement the ISerializable interface.
What you would need to do is make your own class that implements the IDictioanry interface and every time someone calls add, use reflection to check if the element passed in has a serializable attribute (and throw an exception if it doesn't).
Code would look something like
class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> d;
public void Add(TKey key, TValue value)
{
if( value.GetType().IsSerializable )
{
d.Add(key, value);
}
else
{
throw new ArgumentException();
}
}
.....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With