首页 >后端开发 >C++ >如何使用反射在 C# 中调用带有动态类型参数的泛型方法?

如何使用反射在 C# 中调用带有动态类型参数的泛型方法?

Barbara Streisand
Barbara Streisand原创
2025-01-03 14:19:40745浏览

How to Invoke Generic Methods with Dynamic Type Arguments in C# using Reflection?

使用动态类型参数调用泛型方法

在 C# 中,使用仅在执行时已知的类型参数调用泛型方法需要利用反射功能。最初的挑战涉及循环遍历特定命名空间中的接口并使用这些接口作为参数调用通用方法。

要克服这个问题,请按照以下步骤操作:

  1. 找到泛型方法: 使用 Type.GetMethod 检索泛型方法信息。
  2. 创建方法泛型: 使用 MakeGenericMethod 为所需类型创建泛型方法的专用版本。
  3. 调用方法: 对生成的方法调用 Invoke 来执行它。

例如,考虑以下代码:

// 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn