我有一个现有的类,用于将对象序列化和反序列化为 XML 或从 XML 中反序列化。这是一个具有单一类型参数的泛型类 T
其唯一的约束是 where T : IXmlSerializable
.但是,我希望仍然能够在未实现 IXmlSerializable
的类上使用此类。但是有 [Serializable]
属性。我该怎么做呢?
来 self 的通用类:
public static class XmlSerializationUtils<T> where T : IXmlSerializable
{
public static T DeserializeXml(XmlDocument xml) { ... }
public static XmlDocument SerializeToXml(T toSerialize) { ... }
}
我找到了 this discussion但没有给出解决方案,只是我做不到where T : Serializable
.努力做到where T : SerializableAttribute
让 Visual Studio 说“不能使用密封类‘System.SerializableAttribute’作为类型参数约束”。
编辑基于Stephen's answer , 我删除了 XmlSerializationUtils<T>
上的约束并添加了这个静态构造函数:
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"
);
}
}
最佳答案
您可以使用 IsSerializable 检查类型是否可序列化对象类型的属性。
myObj.GetType().IsSerializable
如前所述,这不可能作为通用约束添加,但很可能会在构造函数中进行检查。
关于C# 通用序列化实用程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3291990/