利用反射來初始化自定義泛型成員

直接代碼

 private List<T> CreateListInstance<T>(int Length)
        {
            List<T> tList = new List<T>();
            for (int i = 0; i < Length; i++)
            {
                tList.Add(Activator.CreateInstance<T>());
            }
            return tList;
        }


private void Initialize()
{

            foreach (System.Reflection.PropertyInfo item in this.GetType().GetProperties())
            {
                 if (item.PropertyType == typeof(List<CustomClass1>))
                {
                    item.SetValue(this, CreateListInstance<CustomClass>(5),null);
                    
                }
                else if(item.PropertyType==typeof(List<CustomClass2>))
                {
                    item.SetValue(this, CreateListInstance<CustomClass2>(), null);
                }
            }
}
            

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章