vendredi 14 août 2020

Reflection: Dynamically get type and use to create a List (error: is a variable but is used like a type) [duplicate]

public class Worker<T>
{
  public void Work(T expected)
  {
     // Get a list of all the properties that the incoming object owns
     PropertyInfo[] objectProperties = typeof(T).GetProperties();

     // Grab the first property
     PropertyInfo property = objectProperties [0];

     // Get the property's type
     string propertyType = property.PropertyType.Name;

     // If this item is a list, then lets recreate the list
     if(propertyType.StartsWith("List"))
     {
       Type listType= a[0].GetType();
       List<listType> myList = new List<listType>();
     }
  }
}

In the code above, the following line is wrong:

List<listType> myList = new List<listType>();

How do I dynamically create a list using reflection?

I am getting the error message,

" 'listType' is a variable but is used like a type "





Aucun commentaire:

Enregistrer un commentaire