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

com*_*e73 0 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) =>
Run Code Online (Sandbox Code Playgroud)

是否可以?我在最后一行中传递给 Find 而不是 objType 的是什么?

感谢和问候,

-约翰

Mar*_*sky 6

您必须使用反射 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();
    }
}
Run Code Online (Sandbox Code Playgroud)