lundi 11 janvier 2016

C# Print the values of all members of an object

I am trying to iterate through an object and print all the values for each member of said object.

I've created a test program below

public class Employee : Person
{
    public int  Salary { get; set; }
    public int ID { get; set;}
    public ICollection<ContactInfo> contactInfo { get; set; }
    public EmployeeValue value { get; set; }
    public Employee()
    {
        contactInfo = new List<ContactInfo>();
    }
}

public class Person
{
    public string LastName { get; set; }

    public string FirstName { get; set; }

    public bool IsMale { get; set; }
}

public class ContactInfo
{
    public string email { get; set; }
    public string phoneNumber { get; set; }
}

public class EmployeeValue
{
    public int IQ { get; set; }

    public int Rating { get; set; }
}

I then seed the object with some test data. After the object is populated, I attempt to iterate through all members and display their value.

static void Main(string[] args)
    {
        Seed initSeed = new Seed();
        object obj = initSeed.getSomebody();
        foreach (var p in obj.GetType().GetProperties())
        {

            DisplayProperties(p, obj);

        }           

        Console.WriteLine("done");
        Console.ReadKey(true);
    }

static void DisplayProperties(PropertyInfo p, object obj)
    {
        Type tColl = typeof(ICollection<>);

        Type t = p.PropertyType;
        // If this is a collection of objects
        if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) ||
            t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl))
        {
            System.Collections.IList a = (System.Collections.IList)p.GetValue(obj, null);
            foreach (var b in a)
            {
                foreach(PropertyInfo x in b.GetType().GetProperties())
                {
                    DisplayProperties(x, b);
                }
            }

        }
        // If this is a custom object
        else if (Convert.ToString(t.Namespace) != "System")
        {
            foreach (PropertyInfo nonPrimitive in t.GetProperties())
            {

                DisplayProperties(nonPrimitive, obj);
            }
        }
           // if this is .net framework object
        else
        {
            Console.WriteLine(p.GetValue(obj, null));
        }
    }

The problem occurs when the namespace is != "System" ie, it is a custom object. As seen in this line; "else if (Convert.ToString(t.Namespace) != "System")"

After the fucntion recurses and makes it to the final else statement, I get a {"Object does not match target type."}. Somehow I need to get an object reference to the inner object.

Does anybody have any suggestions?





Aucun commentaire:

Enregistrer un commentaire