vendredi 11 septembre 2015

Iterate through Object List nested within Object using Reflection

I am trying to generate an email based on form input using reflection to make the email in a quicker and hopefully better way.

Iterating through the nested Lists within the Company object so that _body is a long output list of all properties within Company and it's nested object lists (Asn and Contact).

When the method accepts a Company object, it runs through each property in Company and checks what type it is. I'm coming undone on the checking the typeof List<>, I don't know why it isn't iterating through the collection.

I've been faffing with the code all morning but don't seem to be getting anywhere.

Where am I going wrong?

Basic model structure:

public class Company {
public string name {get;set;}
public List<Asn> asns {get;set;}
public List<Contact> contacts {get;set;}
}

public class Asn {
// string/int/bool properties
}
public class Company {
// string/int/bool properties
}

Problem Method code:

    public static void SendEmail(Company cm)
        {
                string _body = "";
                string _subject = "ASN Form Request";

                Type type = cm.GetType();
                Type type2 = cm.asns.GetType();
                Type type3 = cm.contacts.GetType();

                PropertyInfo[] companyProperties = type.GetProperties();
                PropertyInfo[] asnProperties = type2.GetProperties();
                PropertyInfo[] contactProperties = type3.GetProperties();

                foreach(PropertyInfo property in companyProperties)
                {
                    if (property.PropertyType == typeof(string) || property.PropertyType == typeof(int) || property.PropertyType == typeof(bool))
                    _body += property.Name + " = " + property.GetValue(cm, null) + Environment.NewLine;

                    if (property.PropertyType == typeof(List<>)) // not running through the model properties
                        foreach(PropertyInfo asnproperty in asnProperties)
                        {
                            _body += asnproperty.Name + " = " + asnproperty.GetValue(cm, null) + Environment.NewLine;
                        }

                    if(property.PropertyType == typeof(List<>)) // not running through the model properties
                        foreach(PropertyInfo contactproperty in contactProperties)
                        {
                            _body += contactproperty.Name + " = " + contactproperty.GetValue(cm, null) + Environment.NewLine;
                        }
                }
}





Aucun commentaire:

Enregistrer un commentaire