[英]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.