Is it possible to make such code work?:
private List<Type> Models = new List<Type>()
{
typeof(LineModel), typeof(LineDirectionModel), typeof(BusStopTimeModel), typeof(BusStopNameModel)
};
foreach (Type model in Models) // in code of my method
{
Connection.CreateTable<model>(); // error: 'model' is a variable but is used like a type
}
Thanks in advance
You won't be able to use the variable as a generic type using the conventional syntax (CreateTable<model>
). Without knowing what CreateTable
does, you have two options:
Instead of making CreateTable
a generic method, have it take the type as a parameter:
public static void CreateTable(Type modelType)
{
}
Use Reflection to dynamically invoke the generic method using the desired type:
var methodInfo = typeof (Connection).GetMethod("CreateTable");
foreach (Type model in Models)
{
var genericMethod = methodInfo.MakeGenericMethod(model);
genericMethod.Invoke(null, null); // If the method is static OR
// genericMethod.Invoke(instanceOfConnection, null); if it's not static
}
Note that the reflection way would be slower since the method info won't be resolved until runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With