简体   繁体   中英

How to find out if class has DataContract attribute?

I'm writing a serialization function that needs to determine whether class has DataContract attribute. Basically function will use DataContractSerializer if class has DataContract attribute, otherwise it will use XmlSerializer.

Thanks for your help!

The simplest way to test for DataContractAttribute is probably:

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

That said, now that DC supports POCO serialization, it is not complete. A more complete test for DC serializability would be:

bool f = true;
try {
    new DataContractSerializer(typeof(T));
}
catch (DataContractException) {
    f = false;
}
    bool hasDataContractAttribute = typeof(YourType)
         .GetCustomAttributes(typeof(DataContractAttribute), true).Any();

I found that in addition to checking for DataContractAttribute, you should also allow for System.ServiceModel.MessageContractAttribute and 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;

Try something like:

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

bool hasDataContractAttribute = (o != null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM