![](/img/trans.png)
[英]In C#, is it possible to determine the type parameter of a generic at runtime?
[英]C# Determine Generic Type Parameter at Runtime
如果存在命名的 class,我想将该 class 作为类型参数传递给泛型方法。 否则我想传递不同的类型。 我无法弄清楚如何将类型参数传递给泛型方法。
// 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 并传递定义该方法的 class 实例和该方法的必要参数,例如:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.