使用对象属性的反射创建所有对象!

时间:2009-08-26 20:30:58

标签: c#

好的,这是场景!我有一个Person对象,它有一个Address对象。人有一个地址列表。

现在,我想迭代Person的属性,当我到达List时,我想创建一个Address对象的对象。我怎样才能做到这一点?

更新:

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(); 
            }

上面的反射代码返回一个List但它是List类型。我想要通用类型是地址。

1 个答案:

答案 0 :(得分:0)

Tony,如果您有权访问Address类,那么您可以这样做。

 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