简体   繁体   中英

Creating all objects using reflection of an object properties!

Okay here is the scenario! I have a Person object which has an Address object. Person has a list of Addresses.

Now, I want to iterate through the properties of the Person and when I reach a List I want to create an object of the Address object. How can i do that?

Update:

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

        private List<Address> _addresses = new List<Address>(); 

        public void AddAddress(Address address)
        {
            _addresses.Add(address);
            address.Person = this; 
        }

        public List<Address> Addresses  
        {
            get { return _addresses; }
            set { _addresses = value; }
        }
    }
 var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 
            foreach(var property in properties)
            {
                var propertyType = property.PropertyType;

                if (!propertyType.IsGenericType) continue;

                var obj = Activator.CreateInstance(propertyType);

                var genericType = obj.GetType().GetGenericTypeDefinition(); 

                Console.WriteLine(obj.GetType().Name);


                var type = property.GetType(); 
            }

The above reflection code returns me a List but it is of type List. I want the Generic Type which is address.

Tony, if you have access to Address class then you could simply do this.

 var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            List<Address> retVal;
            foreach (var property in properties)
            {
                var propertyType = property.PropertyType;
                if (!propertyType.IsGenericType) continue;


                retVal = property.GetValue(item, new object[] { }) as List<Address>;

                if (retVal != null)
                    break;
            }

            //now you have your List<Address> in retVal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM