Home >Backend Development >C++ >How Can I Call Generic Methods with Runtime-Determined Types?
Calling Generic Methods with Types Determined at Runtime
This issue arises when attempting to call a generic method with a type parameter unknown at compile time. Ordinary method calls rely on type safety checks performed by the compiler, but when the type is only available at runtime, alternative approaches are necessary.
Reflection-Based Solution
In the context of the code example provided:
public void Method<T>() where T : class {} public void AnotherMethod() { ... foreach (var interface in interfaces) { Method<interface>(); // Compile error! } }
To bypass the compile-time type checking:
Retrieve the open generic method using Type.GetMethod:
MethodInfo method = typeof(Test).GetMethod("Method");
Make the method generic with MakeGenericMethod:
MethodInfo genericMethod = method.MakeGenericMethod(interface);
Invoke the method with Invoke:
genericMethod.Invoke(null, null); // No target or arguments in this case
Complete Example
To clarify the process, consider this revised code sample:
using System; using System.Linq; using System.Reflection; namespace Sample { interface IFoo { } interface IBar { } class Program { public static void CallMe<T>() { Console.WriteLine("Type of T: {0}", typeof(T)); } static void Main() { var types = typeof(Program).Assembly.GetTypes().Where(t => t.Namespace == "Sample"); var methodInfo = typeof(Program).GetMethod("CallMe"); foreach (var type in types) { var genericMethodInfo = methodInfo.MakeGenericMethod(type); genericMethodInfo.Invoke(null, null); } } } }
In this example, the generic CallMe method is called dynamically based on the types found in the Sample namespace.
The above is the detailed content of How Can I Call Generic Methods with Runtime-Determined Types?. For more information, please follow other related articles on the PHP Chinese website!