繁体   English   中英

C # 使用不同类型多次调用泛型方法

[英]C # calling generic methods mutiple times with different types

有没有办法在列表(或字典或元组)中存储不同类型(类型名称)并迭代列表以调用列表中每个项目的通用方法?

您可以创建一个System.Type列表,其中存储您要调用泛型方法的所有不同类型。

答案可能会根据您的确切要求而改变,但假设您尝试为 class 的实例调用公共方法,您可以执行以下操作:

var types = new List<System.Type>(); // store all types in this

var genericMethod = instanceOfClassWithGenericMethod.GetType().GetMethod("MethodNameHere"); // you can use `nameof` for method name

foreach (var type in types)
{
    var genericMethodWithType = genericMethod.MakeGenericMethod(type);
    genericMethodWithType.Invoke(instanceOfClassWithGenericMethod, null);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM