how to create a list of type obtained from reflection

后端 未结 3 1613
一个人的身影
一个人的身影 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);
    
    0 讨论(0)
  • 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...");
    
    0 讨论(0)
  • 2021-01-21 14:43

    Try this:

    var listType = typeof(List<>);
    var constructedListType = listType.MakeGenericType(myType);
    
    var myList = (IList)Activator.CreateInstance(constructedListType);
    myList.Add(x);
    

    The list will not be strongly-typed but you can add items as objects.

    0 讨论(0)
提交回复
热议问题