简体   繁体   中英

Generic method with unspecified type possible?

I do need a solution for loading lists of objects - lookups where only one property is referenced from 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; }
}

For the lookup I need a List to be loaded from the database, to know from where to load the information I use an Attribute

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

After reading out the PropertyInfo for the WorkingObject.City Property I know the type of the lookup object, and from which class with which method to load it. Now I need the bridge to get a List with that 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 the typed List<> for using properties of the LookupObjects on the UI, how can I become a useable list in Code?

My ideal Outcome would be, if I could just type:

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

where the parameters are read from the Attribute.

In order to produce a List<T> type, and thus instance, at runtime, where T comes from a Type object (ie. not known at compile-time), you would do this:

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 produce, at runtime, the correct list type and store it in the list variable.

Note that there is no way you can get the compiler to infer the variable type, so this:

var list = Loader.Load(...)

will still not produce a List<T> type , it will have to use a non-generic, known-at-compile-time type to store the list, like IList , but the object you store in it can be a generic one, produced the way I describe above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM