使用保存在变量中的类型调用泛型函数

我有4个看起来像这样的界面:

IBaseInter {}
IInterA : IBaseInter {}
IInterB : IBaseInter {}
IInterC : IBaseInter {}

我需要使用运行时确定的那些接口类型之一来调用函数。基本上我想做这样的事情

Type interfaceType; 
if (condition == 1){
    interfaceType = typeof(IInterA);
}
if (condition == 2){
    interfaceType = typeof(IInterB);
}
if (condition == 3){
    interfaceType = typeof(IInterC);
}

var result = MyFunction<interfaceType>("foo");

public T MyFunction<T>(string val)
{
    // do some work
    ...
    return ClassICantModify.FunctionICantModify<T>(resultOfWork);
}

这会引起以下投诉:'invokerType' is a variable but used like a type

可以做我想做的事吗?我需要以这种方式多次使用interfaceType,因此我想将类型保存在变量中,而不是在每个if中创建result。我在网上发现的所有其他尝试做类似事情的示例似乎都是在创建一个类,而不是调用一个函数,而且似乎没有用。

do11223 回答:使用保存在变量中的类型调用泛型函数

您可以像这样向类添加方法:

public object MyNonGenericFunction(Type t,string value)
        {
            return this.GetType().GetMethod("MyFunction").MakeGenericMethod(t).Invoke(this,new object[]{value});
        }

,您可以像这样使用它:

var result= MyNonGenericFunction(interfaceType,myStringValue);

Microsoft的一篇文章,介绍如何使用MakeGenericMethod从泛型方法调用非泛型方法... https://docs.microsoft.com/en-us/dotnet/api/system.reflection.methodinfo.makegenericmethod?view=netframework-4.8

本文链接:https://www.f2er.com/3169366.html

大家都在问