将类名传递给泛型方法<T>,当类名存储为字符串时



我目前正在处理一个将class作为T传递给GenericMethod的要求。但我将className作为字符串参数。当我在编译时知道className时,我就没有问题了。但是当我收到字符串参数中的className时,我把className作为T传递给GenericMethod。。

如何将className作为类传递给GenericMethodChildClass_1:ParentClass

public override void CallGenericMethod(string currentClassName)
{
var type = Type.GetType(currentClassName);
GenericMethod<type>(typeOf(type).Name);
}

ParentClass.cs

public virtual void GenericMethod<type>(string className){
console.WriteLine("Invoked ClassName");
}

有人能帮我解决这个问题吗。提前感谢

您需要在运行时构建通用方法:

public void CallGenericMethod(string currentClassName)
{
var type = Type.GetType(currentClassName);
var methodInfo = GetType().GetMethod(nameof(GenericMethod));
methodInfo.MakeGenericMethod(type).Invoke(typeOf(type).Name);
}

空安全被省略

最新更新