lundi 11 janvier 2016

Initialise and Search Nested Properties of T

I have an XML serialiser that breaks when the XML returned isn't XML. So to combat this I wanted to display the error in the object returned rather than just null or break.

One of my classes is derived from a class that contains a string error property. Class structure could be two or three classes down.

Using generic reflection, is it possible to access the Message property? Currently when I send in an object that doesn't derive from ClassC it breaks, however as not ever class will be ClassA -> ClassB : ClassC, some could be Class1 -> Class2 -> Class3 : ClassC

Problem code:

var obj = (T)Activator.CreateInstance(typeof(T));
                Type type = obj.GetType();
                PropertyInfo prop = type.GetProperty("message");
                prop.SetValue(obj, Convert.ChangeType(dirtyXml,prop.PropertyType), null);
                return (T)obj;

Two tier class structure:

    Class ClassA {
       ClassB classB {get;set;}
    }

    Class ClassB : ClassC {
       // other properties 
    }

    Class ClassC {
       String Message message {get;set;}
    }





Aucun commentaire:

Enregistrer un commentaire