简体   繁体   English

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

[英]C# Determine Generic Type Parameter at Runtime

If a named class exists, I want to pass that class as the type parameter to a generic method.如果存在命名的 class,我想将该 class 作为类型参数传递给泛型方法。 Otherwise I want to pass a different type.否则我想传递不同的类型。 I cannot figure out how to pass the type parameter to the generic method.我无法弄清楚如何将类型参数传递给泛型方法。

// 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) =>

Is it possible?可能吗? What do I pass to Find in the last line instead of objType?我在最后一行将什么传递给 Find 而不是 objType?

Thanks & regards,感谢和问候,

-John -约翰

You must use the Reflection API.您必须使用反射 API。 Once you get the argument type for your Find method, you need to get a MethodInfo from the Find method and pass an instance of the class that defines that method and the necessary parameters for the method, an example:获得 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.

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