开发者

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 fo开发者_C百科r 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();


Try something like:

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

bool hasDataContractAttribute = (o != null);


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜