Pass An Instantiated System.Type as a Type Parameter for a Generic Class

后端 未结 6 1178
萌比男神i
萌比男神i 2020-11-21 07:46

The title is kind of obscure. What I want to know is if this is possible:

string typeName = ;
Type myType = Type.GetType(         


        
6条回答
  •  我寻月下人不归
    2020-11-21 08:12

    In this snippet I want to show how to create and use a dynamically created list. For example, I'm adding to the dynamic list here.

    void AddValue(object targetList, T valueToAdd)
    {
        var addMethod = targetList.GetType().GetMethod("Add");
        addMethod.Invoke(targetList, new[] { valueToAdd } as object[]);
    }
    
    var listType = typeof(List<>).MakeGenericType(new[] { dynamicType }); // dynamicType is the type you want
    var list = Activator.CreateInstance(listType);
    
    AddValue(list, 5);
    

    Similarly you can invoke any other method on the list.

提交回复
热议问题