【发布时间】:2011-10-07 17:53:31
【问题描述】:
我正在编写一个序列化函数,该函数需要确定类是否具有 DataContract 属性。如果类具有 DataContract 属性,基本上函数将使用 DataContractSerializer,否则将使用 XmlSerializer。
感谢您的帮助!
【问题讨论】:
标签: c# serialization datacontract deserialization
我正在编写一个序列化函数,该函数需要确定类是否具有 DataContract 属性。如果类具有 DataContract 属性,基本上函数将使用 DataContractSerializer,否则将使用 XmlSerializer。
感谢您的帮助!
【问题讨论】:
标签: c# serialization datacontract deserialization
测试 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 编译第二个示例。
bool hasDataContractAttribute = typeof(YourType)
.GetCustomAttributes(typeof(DataContractAttribute), true).Any();
【讨论】:
Any() 比使用 Count() > 0 更好,但在这种情况下,这是学术上的区别。
尝试类似:
object o = this.GetType().GetCustomAttributes(true).ToList().FirstOrDefault(e => e is DataContractAttribute);
bool hasDataContractAttribute = (o != null);
【讨论】:
我发现除了检查 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;
【讨论】: