how to create a list of type obtained from reflection

后端 未结 3 1652
一个人的身影
一个人的身影 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:33

    You need MakeGenericType method:

    var argument = new Type[] { typeof(myType) };
    var listType = typeof(List<>); 
    var genericType = listType.MakeGenericType(argument); // create generic type
    var instance = Activator.CreateInstance(genericType);  // create generic List instance
    
    var method = listType.GetMethod("Add"); // get Add method
    method.Invoke(instance, new [] { argument }); // invoke add method 
    

    Alternatively you can cast your instance to IList and directly use Add method.Or use dynamic typing and don't worry about casting:

    dynamic list = Activator.CreateInstance(genericType);
    list.Add("bla bla bla...");
    

提交回复
热议问题