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

C#在运行时确定泛型类型参数,c#,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

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

// 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) =>
//这种类型存在吗?
Type objType=Type.GetType(typeof(ModelFactory).Name+“+内容类型+”模型);
//如果不是,请改用此类型
if(objType==null)
{
objType=typeof(GenericModel);
}
//传递什么作为泛型类型参数?
var other=query.Find().ContinueWith((t)=>
有可能吗?在最后一行中传递什么来代替objType

谢谢和问候


-John

您必须使用反射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();
    }
}
public类GenericModel{}
//此类模拟包含泛型Find方法的类
公共类查询{
公共无效查找(){
WriteLine(“调用Find方法…”);
}
}
班级计划{
静态异步任务主(字符串[]args){
var theType=typeof(GenericModel);
//从Find方法获取MethodInfo
var method=typeof(Query).GetMethod(nameof(Query.Find)).MakeGenericMethod(类型);
var instanceOfQuery=Activator.CreateInstance(typeof(Query));
var response=method.Invoke(instanceOfQuery,null);//将方法强制转换为find的返回类型。
Console.ReadLine();
}
}

这样的反射往往会“感染”代码的其余部分。您必须获取
查找
方法的MethodInfo,并为您的
T
构造正确的方法版本,然后使用
调用
调用它,但是剩下的
ContinueWith
也将很难掌握。我的建议是将最后一行分离到新的generic方法,并使用反射,正如我在本注释开头所建议的那样,获取此新方法的MethodInfo并为正确的T调用它。可能只是简化了示例。但是,如果您有一个类型可以传递到typeof…那么该类型存在,并且您可以在编写代码时将其用作泛型参数