使用动态类型参数调用泛型方法
在 C# 中,使用仅在执行时已知的类型参数调用泛型方法需要利用反射功能。最初的挑战涉及循环遍历特定命名空间中的接口并使用这些接口作为参数调用通用方法。
要克服这个问题,请按照以下步骤操作:
例如,考虑以下代码:
// Get the generic method MethodInfo method = typeof(Test).GetMethod("CallMe"); // Get the list of interfaces in the specified namespace var types = typeof(Test).Assembly .GetTypes() .Where(t => t.Namespace == "Interfaces"); // Loop through the interfaces foreach (Type type in types) { // Create a specialized generic method MethodInfo genericMethod = method.MakeGenericMethod(type); // Invoke the method with no target or arguments genericMethod.Invoke(null, null); }
在此例如,我们检索“CallMe”泛型方法,为每个接口类型创建专用版本,并反射性地调用它们。
注意:如果您正在处理的接口类型本身就是泛型,请使用 MakeGenericType 而不是 MakeGenericMethod ,传入适当的类型参数。
以上是如何使用反射在 C# 中调用带有动态类型参数的泛型方法?的详细内容。更多信息请关注PHP中文网其他相关文章!