C# 通用序列化实用程序类

标签 c# generics xml-serialization constraints

我有一个现有的类,用于将对象序列化和反序列化为 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/

相关文章:

java - XStream 中没有已知类类型的注释

c# - 比较 Excel 工作表与文本文件

java - 使用泛型有什么好处?

.Net 2.0 - 通用列表的效率如何?

java - 在泛型类中使用泛型对象方法

java - 日期和日期时间应该如何序列化 SOAP (xml) 消息

java - JAXB - 将元素解析为字符串

python - Base 64 字符串和字节数组之间的转换在 C# 和 Python 中有所不同

c# - 动态 where 子句的最简单方法

c# - 用于保留空格的 XAML 等效代码是什么?