I have an existing class for serializing and deserializing objects to/from XML. It's a generic class with a single type parameter T
whose only constraint is where T : IXmlSerializable
. However, I want to still be able to use this class on classes that do not implement IXmlSerializable
but have the [Serializable]
attribute. How could I go about doing this?
From my generic class:
public static class XmlSerializationUtils<T> where T : IXmlSerializable
{
public static T DeserializeXml(XmlDocument xml) { ... }
public static XmlDocument SerializeToXml(T toSerialize) { ... }
}
I found this discussion but there was no solution given, just that I can't do where T : Serializable
. Trying to do where T : SerializableAttribute
makes Visual Studio say "Cannot use sealed class 'System.SerializableAttribute' as type parameter constraint".
Edit: based on Stephen's answer, I removed the constraints on XmlSerializationUtils<T>
and added this static constructor:
static XmlSerializationUtils()
{
Type type = typeof(T);
bool hasAttribute = null != Attribute.GetCustomAttribute(type,
typeof(SerializableAttribute));
bool implementsInterface =
null != type.GetInterface(typeof(IXmlSerializable).FullName);
if (!hasAttribute && !implementsInterface)
{
throw new ArgumentException(
"Cannot use XmlSerializationUtils on class " + type.Name +
" because it does not have the Serializable attribute " +
" and it does not implement IXmlSerializable"
);
}
}