Possible generic method with undefined type?

I need a solution for loading lists of objects - search queries in which only one property refers to the current object, as in this example.

class LookupObjectAddress { [...] public string City { get; set; } [...] } class WorkingObject { // references the property from LookupObjectAddress public string City { get; set; } } 

To search, I need a List that needs to be downloaded from the database, to find out where to download information, I use the attribute

 class WorkingObject { // references the property from LookupObjectAddress [Lookup(Type=typeof(LookupObjectAddress), staticloaderclass="LookupObjLoader", staticloaderMethod="LookupObjLoadMethod")] public string City { get; set; } } 

After reading PropertyInfo for the WorkingObject.City property, I know the type of the search object and from which class, with which method to load it. Now I need a bridge to get a list with three parameters to work with.

 Type loaderClass = Type.GetType(classname); MethodInfo loaderMethod = loaderClass.GetMethod(loadmethod); object objList = loaderMethod.Invoke(null, new object[] {}); 

Since I need a typed List <> to use the LookupObjects properties in the user interface, how can I become a useful list in Code?

My ideal result would be if I could just type:

 var list = Loader.Load(type, "LookupObjLoader", "LookupObjLoadMethod"); 

where the parameters are read from the attribute.

+4
source share
1 answer

To create a List<T> and thus an instance at runtime, where T comes from a Type object (i.e., unknown at compile time), you do the following:

 Type genericListType = typeof(List<>); // yes, this really is legal syntax Type elementType = ... Type specificListType = genericListType.MakeGenericType(elementType); // specificListType now corresponds to List<T> where T is the same type // as elementType IList list = (IList)Activator.CreateInstance(specificListType); 

This will result in the correct type of list at runtime and store it in the list variable.

Note that you cannot force the compiler to infer the type of a variable so that this:

 var list = Loader.Load(...) 

still won't create a List<T> , to store the list, it should not use the general type known at the time of compilation, for example IList , but the object that you store in it can be a general one, created in the way described above.

+5
source

All Articles