简体   繁体   English

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

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

Is there a way to store different types (names of types) in a List (or dictionary or tuples) and iterate the list to call a generic method for each item in the list?有没有办法在列表(或字典或元组)中存储不同类型(类型名称)并迭代列表以调用列表中每个项目的通用方法?

You can create a list of System.Type which stores all the different types you want to call the generic method with.您可以创建一个System.Type列表,其中存储您要调用泛型方法的所有不同类型。

The answer can change based on your exact requirements, but assuming you are trying to call a public method for an instance of a class, you can do something like the following:答案可能会根据您的确切要求而改变,但假设您尝试为 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