C#在运行时确定泛型类型参数



如果存在命名类,我希望将该类作为类型参数传递给泛型方法。否则我想传递一个不同的类型。我不知道如何将类型参数传递给泛型方法。

// Does this type exist?
Type objType = Type.GetType(typeof(ModelFactory).Name + "." + content_type + "Model");
// if not, use this type instead
if (objType == null)
{
objType = typeof(GenericModel);
}
// what to pass as the generic type argument?
var other = query.Find<objType>().ContinueWith((t) =>

有可能吗?我在最后一行传递给Find而不是objType的内容是什么?

谢谢&问候,

-约翰·

您必须使用反射API。获得Find方法的参数类型后,您需要从Find方法获得MethodInfo,并传递定义该方法的类的实例和该方法所需的参数,例如:

public class GenericModel {}
// This class simulates the class that contains the generic Find method
public class Query {
public void Find<T>() {
Console.WriteLine("Invoking Find method...");
}
}
class Program {
static async Task Main(string[] args) {
var theType = typeof(GenericModel);
// Obtaining a MethodInfo from the Find method
var method = typeof(Query).GetMethod(nameof(Query.Find)).MakeGenericMethod(theType);
var instanceOfQuery = Activator.CreateInstance(typeof(Query));
var response = method.Invoke(instanceOfQuery, null); // Cast the method to your return type of find.
Console.ReadLine();
}
}

最新更新