我正在编写一个序列化函数,需要确定类是否具有DataContract属性。如果类具有DataContract属性,则该函数将使用DataContractSerializer,否则将使用XmlSerializer。
感谢您的帮助!
我正在编写一个序列化函数,需要确定类是否具有DataContract属性。如果类具有DataContract属性,则该函数将使用DataContractSerializer,否则将使用XmlSerializer。
感谢您的帮助!
检测DataContractAttribute最简单的方法可能是:
bool f = Attribute.IsDefined(typeof(T), typeof(DataContractAttribute));
话虽如此,现在DC支持POCO序列化,但它并不完整。更完整的DC可序列化性测试应该是:
bool f = true;
try {
new DataContractSerializer(typeof(T));
}
catch (DataContractException) {
f = false;
}
bool hasDataContractAttribute = typeof(YourType)
.GetCustomAttributes(typeof(DataContractAttribute), true).Any();
Any()
通常比使用Count() > 0
更好,无论是性能还是可读性,但在这种情况下,这是一个学术上的区别。 - dbkk尝试类似这样的内容:
object o = this.GetType().GetCustomAttributes(true).ToList().FirstOrDefault(e => e is DataContractAttribute);
bool hasDataContractAttribute = (o != null);
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;