how to create a list of type obtained from reflection

后端 未结 3 1643
一个人的身影
一个人的身影 2021-01-21 14:04

I have a code which looks like this :

Assembly assembly = Assembly.LoadFrom(\"ReflectionTest.dll\");
Type myType = assembly.GetType(@\"ReflectionTest.TestObject\         


        
3条回答
  •  死守一世寂寞
    2021-01-21 14:28

    var listType = typeof(List<>).MakeGenericType(myType)
    var list = Activator.CreateInstance(listType);
    
    var addMethod = listType.GetMethod("Add");
    addMethod.Invoke(list, new object[] { x });
    

    You might be able to cast to IList and call Add directly instead of looking up the method with reflection:

    var list = (IList)Activator.CreateInstance(listType);
    list.Add(x);
    

提交回复
热议问题