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

15

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

感谢您的帮助!

4个回答

20

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

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

话虽如此,现在DC支持POCO序列化,但它并不完整。更完整的DC可序列化性测试应该是:

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

将此答案设置为已接受,因为我不必获取所有属性。 - Alex
我只能使用“InvalidDataContractException”编译第二个示例。 - downwitch

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

不错的回答。在LINQ中,使用Any()通常比使用Count() > 0更好,无论是性能还是可读性,但在这种情况下,这是一个学术上的区别。 - dbkk
如果你有一个类的对象,最好用this.GetType()替换typeof(YourType)。 - Michael Freidgeim

0

尝试类似这样的内容:

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

bool hasDataContractAttribute = (o != null);

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接