Подтвердить что ты не робот

Как узнать, имеет ли класс атрибут DataContract?

Я пишу функцию сериализации, которая должна определить, имеет ли класс атрибут DataContract. В основном функция будет использовать DataContractSerializer, если класс имеет атрибут DataContract, в противном случае он будет использовать XmlSerializer.

Спасибо за вашу помощь!

4b9b3361

Ответ 1

Простейшим способом тестирования DataContractAttribute является, вероятно, следующее:

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

Тем не менее, теперь, когда DC поддерживает сериализацию POCO, он не является полным. Более полным испытанием для сериализуемости DC будет:

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

Ответ 2

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

Ответ 3

Попробуйте что-то вроде:

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

bool hasDataContractAttribute = (o != null);

Ответ 4

Я обнаружил, что помимо проверки 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;