日期:2014-05-16  浏览次数:20978 次

反射动态创建List<T>

    /// <summary>
    /// 语言:C#
    /// 版本:4.0
    /// 环境:vs2010
    /// </summary>
    public class Program
    {
        static void Main(string[] args)
        {
            
            Student tempStu = new Student();
            //获取属性ParentInfoList
            var tempListProperty = tempStu.GetType().GetProperty("ParentInfoList");
            //通过属性的类型,动态创建对象
            //
            //问题1:这里的值永远为null
            var tempList = tempStu.GetType().Assembly.CreateInstance(tempListProperty.PropertyType.FullName);
            tempListProperty.SetValue(tempStu, tempList, null);
            var tempTest = typeof(ParentInfo).Assembly.CreateInstance("ConsoleApplication20.Test");
            //问题2:这里会提示类型不匹配
            tempListProperty.PropertyType.GetMethod("Add").Invoke(tempStu, new Object[] { tempTest });
        }
    }
    public class Student
    {
        public List<ParentInfo> ParentInfoList { get; set; }
        public String ID { get; set; }
    }
    public class ParentInfo
    {
        public String Name { get; set; }
        public String Birthday { get; set; }
    }

------解决方案--------------------
第一个问题:
Activator.CreateInstance(tempListProperty.PropertyType);
不要用GetType.Assembly那种方式闯将。具体为什么我不知道,只是用前者可以成功,后者就是null
期待牛牛给出解释

第二个问题:
Invoke(tempStu, new Object[] { tempTest });
第一个参数不对,应该是Property所属的对象,在该问题中,第一个参数应为tempList
------解决方案--------------------
本帖最后由 caozhy 于 2011-07-06 18:22:48 编辑
引用:
C# code

var list = typeof(List<>).MakeGenericType(typeof(ParentInfo));

学习。lz可以试下。
------解决方案--------------------
贴个完整点的:

var listType = typeof(List<>).MakeGenericType(typeof(ParentInfo));
var list = Activator.CreateInstance(listType);
var addMethod&n