jeudi 1 avril 2021

Check if a class property is string compatiable?

I am using reflection to find all the string compatible properties in an object graph.

I am consuming a 3rd party's XML. They provide me with the POCO classes, but sometimes they do weird things like having a property in a class called Item that is declared as object but it can have a backing type as a string or of another of their classes.

Here is a property

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("BuiltInScript", typeof(TypeBuiltInScript))]
[System.Xml.Serialization.XmlElementAttribute("CloseScreen", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("OpenScreen", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("ResetTag", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("SetTag", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("ToggleTag", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("VBScript", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public object Item
{
    get
    {
        return this.itemField;
    }
    set
    {
        this.itemField = value;
    }
}

This is the section of my code that finds all of the properties of type string this issue it is seems to only work if the POCO class has a property declared as a string and not object

Is there a way to do a compatibility check to see if it can be cast as a string?

PropertyInfo[] proInfoForStrings = objectToEvaluate.GetType().GetProperties()
                        .Where(x => x.PropertyType == typeof(string)).ToArray();




Aucun commentaire:

Enregistrer un commentaire