【问题标题】:How to find out if class has DataContract attribute?如何找出类是否具有 DataContract 属性?
【发布时间】:2011-10-07 17:53:31
【问题描述】:

我正在编写一个序列化函数,该函数需要确定类是否具有 DataContract 属性。如果类具有 DataContract 属性,基本上函数将使用 DataContractSerializer,否则将使用 XmlSerializer。

感谢您的帮助!

【问题讨论】:

    标签: c# serialization datacontract deserialization


    【解决方案1】:

    测试 DataContractAttribute 的最简单方法可能是:

    bool f = Attribute.IsDefined(typeof(T), typeof(DataContractAttribute));
    

    也就是说,现在 DC 支持 POCO 序列化,还不完整。更完整的 DC 可串行化测试是:

    bool f = true;
    try {
        new DataContractSerializer(typeof(T));
    }
    catch (DataContractException) {
        f = false;
    }
    

    【讨论】:

    • 将此答案设置为已接受,因为我不必获取所有属性。
    • 我只能使用InvalidDataContractException 编译第二个示例。
    【解决方案2】:
        bool hasDataContractAttribute = typeof(YourType)
             .GetCustomAttributes(typeof(DataContractAttribute), true).Any();
    

    【讨论】:

    • 不错的答案。在 LINQ 中,在性能和可读性方面,通常使用 Any() 比使用 Count() > 0 更好,但在这种情况下,这是学术上的区别。
    • 如果你有类的对象,最好用this.GetType()替换typeof(YourType)
    【解决方案3】:

    尝试类似:

    object o = this.GetType().GetCustomAttributes(true).ToList().FirstOrDefault(e => e is DataContractAttribute);
    
    bool hasDataContractAttribute = (o != null);
    

    【讨论】:

      【解决方案4】:

      我发现除了检查 DataContractAttribute 之外,您还应该允许 System.ServiceModel.MessageContractAttribute 和 System.SerializableAttribute。

      bool canDataContractSerialize = (from x in value.GetType().GetCustomAttributes(true)
                                       where x is System.Runtime.Serialization.DataContractAttribute
                                       | x is System.SerializableAttribute
                                       | x is System.ServiceModel.MessageContractAttributex).Any;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-20
        • 2011-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多