如何确定类是否具有DataContract属性?

时间:2011-07-18 14:25:08

标签: c# serialization datacontract deserialization

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

感谢您的帮助!

4 个答案:

答案 0 :(得分:18)

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

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

那就是说,既然DC支持POCO序列化,它就不完整了。对DC可串行化的更完整测试将是:

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

答案 1 :(得分:7)

    bool hasDataContractAttribute = typeof(YourType)
         .GetCustomAttributes(typeof(DataContractAttribute), true).Any();

答案 2 :(得分:0)

尝试类似:

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

bool hasDataContractAttribute = (o != null);

答案 3 :(得分:0)

我发现除了检查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;