类未知时使用泛型类型进行反射

时间:2019-09-14 23:44:30

标签: c# reflection

我正在使用反射加载模型:

private void LoadAssemblies()
{
    Assembly assembly = Assembly.LoadFrom(modelDll);
    var types = assembly.GetTypes();

    inputType = assembly.GetType(types.Where(x => x.FullName.Contains("Input")).FirstOrDefault().FullName);
    outputType = assembly.GetType(types.Where(x => x.FullName.Contains("Output")).FirstOrDefault().FullName);

    inputModel = Activator.CreateInstance(inputType);
    outputModel = Activator.CreateInstance(outputType);

    inputModel = JsonConvert.DeserializeObject(jsonPredict);
}

然后我需要调用具有两种泛型类型的方法

// I can't convert this model loaded at runtime into a type to this generic method
var predEngine = mlContext.Model.CreatePredictionEngine<typeof(inputModel), typeof(outputModel)>(mlModel); 

我尝试过

var instance = Activator.CreateInstance(typeof(ModelOperationsCatalog)); 

/* I get an error:
System.MissingMethodException: 'No parameterless constructor defined for this object.'

instance.GetType()
        .GetMethod("CreatePredictionEngine")
        .MakeGenericMethod(inputType, outputType)
        .Invoke(this, new object[] { });
*/

1 个答案:

答案 0 :(得分:1)

创建上下文

var mlContext = new MLContext();

获取模型

var model = mlContext.Model;

然后在其上调用通用方法,将实例和参数传递给它:

 typeof(ModelOperationsCatalog)
            .GetMethod("CreatePredictionEngine")
            .MakeGenericMethod(inputType, outputType)
            .Invoke(instance, new object[] { param1, param2 });*/